﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using LKVMLMLib;
using System.Globalization;
using System.Configuration;
using System.Net.Mail;
using System.Net;

namespace LKVService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Transaction" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Transaction.svc or Transaction.svc.cs at the Solution Explorer and start debugging.
    public class Transaction
    {
        public void AfterAddFund(int user_id, double amount, string OrderID, DateTime? Date, int paymentMethod)
        {
            object[] parameters = { user_id, amount, OrderID, Date };
            string connection = DuAnDaCapEntities.getDomain();
            using (var staticdb = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var cUser = staticdb.UserProfiles.Where(w => w.UserId == user_id).SingleOrDefault();
                if (cUser == null)
                    return;
                switch (paymentMethod)
                {
                    case 1:
                        this.DivideMoney(user_id, amount, OrderID, Date);
                        break;
                    case 2:
                    //bitcoid
                    default:
                        break;
                }
            }
        }
        private void DivideMoney(int user_id, double amount, string OrderID, DateTime? Date)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                try
                {
                    PerfectMoney pe = new PerfectMoney();
                    var userSend = db.CashBankConfigs.Where(w => w.Type == "main").SingleOrDefault();
                    var accountSend = db.PerfectMoneyUsers.Where(w => w.UserId == userSend.UserId).FirstOrDefault();
                    if (accountSend == null)
                        return;

                    var cash_config = db.CashBankConfigs.Where(w => w.Type == "cash").SingleOrDefault();

                    var fund_config = db.CashBankConfigs.Where(w => w.Type == "fund").SingleOrDefault();
                    var lsSub = db.CashBankConfigs.Where(w => w.Type == "sub").ToList();


                    var userCash = db.UserProfiles.Where(w => w.UserId == cash_config.UserId).FirstOrDefault();
                    var userFund = db.UserProfiles.Where(w => w.UserId == fund_config.UserId).FirstOrDefault();
                    if (userCash != null)
                    {
                        var accountCash = db.PerfectMoneyUsers.Where(w => w.UserId == userCash.UserId).FirstOrDefault();
                        var amCash = (cash_config.Percent * amount) / 100;
                        if (accountCash != null)
                        {
                            WalletHistory wl = new WalletHistory();
                            var kq = pe.Transfer(accountSend.Account, accountSend.Password, accountSend.Payer, accountCash.Payer, Math.Round(amCash.Value, 2), 1, 123);
                            if (kq.ContainsKey("ERROR"))
                            {
                                wl.Amount = 0;
                                wl.CreateDate = DateTime.Now;
                                wl.Description = kq["ERROR"].ToString() + " when send " + Math.Round(amCash.Value, 2).ToString() + " to " + accountCash.UserId + "";
                                wl.UserId = accountSend.UserId;
                                db.WalletHistories.Add(wl);
                            }
                            else
                            {
                                wl.Amount = Math.Round(amCash.Value, 2);
                                wl.CreateDate = DateTime.Now;
                                wl.Description = "[DivideMoney]Send " + Math.Round(amCash.Value, 2) + " from " + accountSend.UserId + " to " + accountCash.UserId;
                                wl.UserId = userCash.UserId;
                                db.WalletHistories.Add(wl);
                                //this.chargeFormWallet(userCash.UserId, null, (float)Math.Round(amCash.Value, 2), "[DivideMoney]Send " + Math.Round(amCash.Value, 2) + " from " + accountSend.UserId + " to " + accountCash.UserId + "");
                            }
                        }
                    }
                    if (userFund != null)
                    {
                        var accountFund = db.PerfectMoneyUsers.Where(w => w.UserId == userFund.UserId).FirstOrDefault();
                        var amFund = (fund_config.Percent * amount) / 100;
                        WalletHistory wl = new WalletHistory();
                        if (accountFund != null)
                        {
                            var kq = pe.Transfer(accountSend.Account, accountSend.Password, accountSend.Payer, accountFund.Payer, Math.Round(amFund.Value, 2), 1, 123);
                            if (kq.ContainsKey("ERROR"))
                            {
                                wl.Amount = 0;
                                wl.CreateDate = DateTime.Now;
                                wl.Description = kq["ERROR"].ToString() + "when send " + Math.Round(amFund.Value, 2).ToString() + " to " + accountFund.UserId + "";
                                wl.UserId = accountSend.UserId;
                                db.WalletHistories.Add(wl);
                            }
                            else
                            {
                                wl.Amount = Math.Round(amFund.Value, 2);
                                wl.CreateDate = DateTime.Now;
                                wl.Description = "[DivideMoney]Send " + Math.Round(amFund.Value, 2) + " from " + accountSend.UserId + " to " + accountFund.UserId;
                                wl.UserId = accountFund.UserId;
                                db.WalletHistories.Add(wl);
                                //this.chargeFormWallet(accountFund.UserId,null,(float)Math.Round(amFund.Value, 2),"[DivideMoney]Send " + Math.Round(amFund.Value, 2) + " from " + accountSend.UserId + " to " + accountFund.UserId + "");
                            }

                        }
                    }
                    if (lsSub.Count > 0)
                    {

                        foreach (var item in lsSub)
                        {
                            var amSub = (item.Percent * amount) / 100;

                            var accountSub = db.PerfectMoneyUsers.Where(w => w.UserId == item.UserId).FirstOrDefault();
                            if (accountSub != null)
                            {
                                var kq = pe.Transfer(accountSend.Account, accountSend.Password, accountSend.Payer, accountSub.Payer, Math.Round(amSub.Value, 2), 1, 123);
                                WalletHistory wl = new WalletHistory();
                                if (kq.ContainsKey("ERROR"))
                                {
                                    wl.Amount = 0;
                                    wl.CreateDate = DateTime.Now;
                                    wl.Description = kq["ERROR"].ToString() + "when send " + Math.Round(amSub.Value, 2).ToString() + " to " + accountSub.UserId + "";
                                    wl.UserId = accountSend.UserId;
                                    db.WalletHistories.Add(wl);
                                }
                                else
                                {
                                    wl.Amount = Math.Round(amSub.Value, 2);
                                    wl.CreateDate = DateTime.Now;
                                    wl.Description = "[DivideMoney]Send " + Math.Round(amSub.Value, 2) + " from " + accountSend.UserId + " to " + accountSub.UserId + "";
                                    wl.UserId = accountSub.UserId;
                                    db.WalletHistories.Add(wl);
                                    //this.chargeFormWallet(accountSub.UserId, null, (float)Math.Round(amSub.Value, 2), "[DivideMoney]Send " + Math.Round(amSub.Value, 2) + " from " + accountSend.UserId + " to " + accountSub.UserId + "");
                                }

                            }
                        }
                    }
                    db.SaveChanges();
                }
                catch (Exception e)
                { }
            }
            // chổ này em chia tiền giup anh. theo ty lệ phần trăm như trong bảng cashbankconfig cho các thằng user có user cash, fund, sub
            // rieng thang sub sẽ có nhieu thang: sub1, sub2, sub3,.... cac thang do chia deu nhau.
        }
        public WalletList[] getWallet(int userID)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //var result = db.Wallets.ToArray();
                var result = db.Wallets.Join(db.Wallet_Detail, c => c.Id, p => p.WalletID, (c, p) => new { wallet = c, detail = p })
                    .Where(x => x.detail.UserID == userID && x.wallet.Withdraw == true)
                    .Select(s => new WalletList()
                    {
                        Id = s.wallet.Id,
                        Name = s.wallet.Name,
                        Balance = s.detail.Balance
                    }).ToArray();
                return result;
            }
        }
        public Wallet_Detail getWalletDetail(int UserID, int WalletID)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //var result = db.Wallets.ToArray();
                var result = db.Wallet_Detail.Where(w => w.UserID == UserID && w.WalletID == WalletID).FirstOrDefault();
                return result;
            }
        }
        public List<WalletHistoryView> getWalletsHistory(int UserID, int WalletId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //var result = db.Wallets.ToArray();
                var result = db.WalletHistories.Where(w => w.UserId == UserID && w.WalletId == WalletId).AsEnumerable().OrderByDescending(o => o.CreateDate)
                    .Select(s => new WalletHistoryView()
                    {
                        Amount = (double)s.Amount,
                        Date = s.CreateDate.ToString("dd/MM/yyyy"),
                        Transaction = s.Description,
                    }).ToList();

                return result;
            }
        }
        public List<Wallet> listWallet()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //var result = db.Wallets.ToArray();
                List<Wallet> result = db.Wallets.ToList();
                return result;
            }
        }
        public WalletList[] WalletIn(List<int> IDs)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //var result = db.Wallets.ToArray();
                WalletList[] result = db.Wallets.Where(w => IDs.Contains(w.Id))
                      .Select(s => new WalletList()
                      {
                          Id = s.Id,
                          Name = s.Name,
                      }).ToArray();
                return result;
            }
        }
        public WalletList[] WalletIn(List<int> IDs, int UserId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //var result = db.Wallets.ToArray();
                WalletList[] result = db.Wallets.Where(w => IDs.Contains(w.Id) && w.Withdraw == true).AsEnumerable()
                      .Select(s => new WalletList()
                      {
                          Id = s.Id,
                          Name = s.Name + ": Ƀ" + db.Wallet_Detail.Where(w => w.UserID == UserId && w.WalletID == s.Id).FirstOrDefault().Balance.ToString("0.00"),
                      }).ToArray();
                return result;
            }
        }
        public List<PaymentMethod> GetPaymentMethods()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //var result = db.Wallets.ToArray();
                List<PaymentMethod> result = db.PaymentMethods.ToList();
                return result;
            }
        }
        public Dashboard getDashboard(int userID)
        {
            LKVService.User db = new LKVService.User();
            var Gconfig = new LKVService.OrderService();
            var profit = new LKVService.ProfitService();
            var ROI = Gconfig.GetGConfig().ROI.Value;
            var level = "";
            if (db.findAchievementByUserId(userID) != null) level = db.findAchievementByUserId(userID).Name;
            int Referral = db.getListByParent(userID).Count();
            int Running = this.getTotalRunningPackByUserID(userID, ROI);
            int Expired = this.getTotalExpiredPackByUserID(userID, ROI);
            //double Share = this.getShareByUserID(userID);
            double TotalInvest = this.getTotalInvestbyUser(userID).Value;
            double? Withdrawals = this.getTotalWithdrawals(userID);
            double? Commission = this.getTotalCommission(userID);
            double? SponsorBonus = profit.findProfitbyUserID(userID).Sum(w => w.Amount);
            double? riskWallet = this.getWalletDetail(userID,1).Balance;
            List<WalletList> wallets = this.getWallet(userID).ToList();
            List<StatisticList> list = new List<StatisticList>()
            {
                new StatisticList {Id=1,Name="Referral", Total=Referral.ToString(), Link="#/app/referrals",isMoney=false},
                new StatisticList {Id=2,Name="Running package", Total=Running.ToString(), Link="#/app/packruning",isMoney=false},
                new StatisticList {Id=2,Name="Total Invest", Total=TotalInvest.ToString(), Link="#",isMoney=true},                
                //new StatisticList {Id=3,Name="Total Commission", Total=Commission>0?Commission.Value.ToString ("0.00"):"0", Link="#"},           
                //new StatisticList {Id=4,Name="Share", Total=Share>0?Share.ToString():"0", Link="#/app/walletmanage"},                
            };
            Dashboard result = new Dashboard()
            {
                totalwithdrawals = Withdrawals,
                Statistic = list,
                Wallets = wallets,
                level = level,
                sponsorBonus = SponsorBonus,
                riskWallet = riskWallet
            };
            return result;
        }
        /**
         *Get total share for user 
         */
        public double getShareByUserID(int userID)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //var result = db.Wallets.ToArray();
                double r = 0;
                var result = db.Share_User.Where(x => x.UserId == userID).ToList();
                if (result.Count > 0)
                    r = result.Sum(s => s.Balance);
                return r;
            }
        }
        /**
         *@summary Get total Running Pack for userid
         *@param name="userID"
         *@by tantrinh
         */
        public int getTotalRunningPackByUserID(int userID, double ROI)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //var result = db.Wallets.ToArray();
                var result = db.Orders.Where(x => x.Percent < ROI && x.UserId == userID).Count();
                return result;
            }
        }
        /**
         *@summary Get total Expired Pack for userid
         *@param name="userID"
         *@returns Tong goi
         *@by tantrinh
         */
        public int getTotalExpiredPackByUserID(int userID, double ROI)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //var result = db.Wallets.ToArray();
                var result = db.Orders.Where(x => x.Percent >= ROI && x.UserId == userID).Count();
                return result;
            }
        }
        public double? getTotalInvestbyUser(int userID)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var result = db.Orders.Where(w => w.UserId == userID).Sum(s => s.Amount);
                if (result != null)
                {
                    return result.Value;
                }
                return 0;
            }
        }
        /**
         *@summary Get Running Pack for userid voi ROI 
         *@param name="userID"
         *@returns Tong goi
         *@by tantrinh
         */
        public ManagerPack[] getRunningPackByUserID(int userID, double ROI)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //var result = db.Wallets.ToArray();
                //var result = db.Orders.Where(x => x.Percent >= ROI && x.UserId == userID).ToArray();
                var rt = db.Orders.Where(w => w.UserId == userID && w.Percent < ROI)
                    .AsEnumerable()
                    .Select(s => new ManagerPack()
                    {
                        Id = s.ID,
                        Percent = s.Percent,
                        Title = s.ID_Order,
                        Amount = s.Amount.Value,
                        CreateDate = s.Date.Value.ToString("dd-MM-yyyy"),
                    })
                    .ToArray();
                return rt;
            }
        }
        /**
         *@summary Get Running Pack for userid voi ROI >=150
         *@param name="userID"
         *@returns ManagerPack
         *@by tantrinh
         */
        public ManagerPack[] getExpiresPackByUserID(int userID, double ROI)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //var result = db.Wallets.ToArray();
                //var result = db.Orders.Where(x => x.Percent >= ROI && x.UserId == userID).ToArray();
                var rt = db.Orders
                    .Where(w => w.UserId == userID && w.Percent >= ROI)
                    .Select(s => new ManagerPack()
                    {
                        Id = s.ID,
                        Percent = (int)s.Percent,
                        Title = s.ID_Order
                    }).ToArray();
                return rt;
            }
        }
        /**
         *@summary Get total Withdrawals for userid
         *@param name="userID"
         *@returns Tong goi
         *@by tantrinh
         */
        public double? getTotalWithdrawals(int userID)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var result = db.Withdrawals.Where(x => x.UserId == userID).Sum(s => s.Amout);
                return result;
            }
        }
        public double? getTotalCommission(int userID)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {

                db.Configuration.ProxyCreationEnabled = false;
                //var result = db.Wallets.ToArray();                
                //var result = db.Profits.Where(x => x.UserId == userID).Where(w => w.ProfitType == "HoaHongSponsorPack" || w.ProfitType == "HoaHongPackLine" || w.ProfitType == "HoaHongDailyPay").Sum(s => s.Amount);
                var result = db.Profits.Where(x => x.UserId == userID).Sum(s => s.Amount);
                if (result != null)
                {
                    return result.Value;
                }
                return 0;
            }
        }
        public double? getTotalUpgradeCommission(int userID)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var result = db.Profits.Where(x => x.UserId == userID).Where(w => w.ProfitType == "HoaHongUpgrade").Sum(s => s.Amount);
                if (result != null)
                {
                    return result.Value;
                }
                return 0;
            }
        }
        public double getCashoutFee()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var val = db.FeeConfigs.FirstOrDefault();
                if (val != null)
                    return (double)val.Cashout;
                return 0;
            }
        }
        /**
         *@summary ham tru tien trong wallet
         *@param name="userID"
         *@returns Tong goi
         *@by tantrinh
         */
        public bool chargeFormWallet(int userID, int? WalletID, double Amount, string desc, string orderbatch = "", int? Payment_Method = null)
        {
            Amount = Math.Round(Amount, 8);
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //get tien trong vi
                Wallet_Detail moneyUser = db.Wallet_Detail.Where(w => w.UserID == userID && w.WalletID == WalletID).SingleOrDefault();
                if (moneyUser == null) return false;
                if (moneyUser.Balance >= -1 * Amount)
                {
                    //tru tien trong vi
                    moneyUser.Balance += Amount;
                    var walletHistory = new WalletHistory();
                    walletHistory.UserId = userID;
                    walletHistory.Amount = Amount;
                    walletHistory.CreateDate = DateTime.Now;
                    walletHistory.WalletId = WalletID;
                    walletHistory.Description = desc;
                    walletHistory.Payment_orderid = orderbatch;
                    walletHistory.PaymentMethod = Payment_Method;
                    db.WalletHistories.Add(walletHistory);
                }
                else
                {
                    //khong du tien de thanh khoan
                    return false;
                }
                //var result = db.Wallets.ToArray();
                db.SaveChanges();
                return true;
            }
        }
        public bool CheckInBuyPack(int UserId, float Amount)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var user = db.UserProfiles.Where(w => w.UserId == UserId).SingleOrDefault();
                var UserLevel = db.UserLevels.Where(w => w.Id == user.Level).SingleOrDefault();
                if (Amount <= UserLevel.Maximum && Amount >= UserLevel.Minimum)
                {
                    return true;
                }
            }
            return false;
        }
        public PerfectMoneyUser getAccountPerfectMoney(int UserID)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var perfectAccount = db.PerfectMoneyUsers.Where(w => w.UserId == UserID).FirstOrDefault();
                //var result = db.Wallets.ToArray();
                return perfectAccount;
            }
        }
        public int UpdatePerfectMoneyTransaction(formPerfectTransaction data)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var perfectTransaction = new LKVMLMLib.PerfectMoneyTransaction();
                    if (data.Id > 0)
                    {
                        //update
                        var PerfectMoneyTransaction = db.PerfectMoneyTransactions.Where(w => w.Id == data.Id).FirstOrDefault();
                        PerfectMoneyTransaction.Payment_Amount = data.Payment_Amount;
                        PerfectMoneyTransaction.Payee_Account = data.Payee_Account;
                        PerfectMoneyTransaction.Payee_Name = data.Payee_Name;
                        PerfectMoneyTransaction.Payer_Account = data.Payer_Account;
                        PerfectMoneyTransaction.Payment_Units = data.Payment_Units;
                        PerfectMoneyTransaction.TimeStampgmt = data.TimeStampgmt;
                        PerfectMoneyTransaction.V2_Hash = data.V2_Hash;
                        PerfectMoneyTransaction.Payment_Batch_Num = data.Payment_Batch_Num;
                        PerfectMoneyTransaction.Modifi_Date = DateTime.Now;
                        db.SaveChanges();
                        return PerfectMoneyTransaction.Id;
                    }
                    else
                    {
                        //add                        
                        perfectTransaction.Payment_Amount = data.Payment_Amount;
                        perfectTransaction.Payee_Account = data.Payee_Account;
                        perfectTransaction.Payee_Name = data.Payee_Name;
                        perfectTransaction.Payer_Account = data.Payer_Account;
                        perfectTransaction.Payment_Units = "USD";
                        perfectTransaction.UserId = data.UserId;
                        perfectTransaction.Create_Date = DateTime.Now;
                        db.PerfectMoneyTransactions.Add(perfectTransaction);
                        db.SaveChanges();
                        return perfectTransaction.Id;
                    }
                    //var result = db.Wallets.ToArray();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        public formPerfectTransaction getPerfectMoneyTransaction(int Id)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                string domain = DuAnDaCapEntities.getDomain();
                if (domain == "localhost")
                    domain = "http://" + DuAnDaCapEntities.getDomain() + ":12385";
                else domain = "http://" + DuAnDaCapEntities.getDomain();
                var configfee = db.FeeConfigs.FirstOrDefault();

                db.Configuration.ProxyCreationEnabled = false;
                var UserDB = new LKVService.User();
                var userAdmin = UserDB.getUserByGroup(3);
                var PerfectMoneyAdmin = this.getAccountPerfectMoney(userAdmin.UserId);
                var perfectTransaction = db.PerfectMoneyTransactions.Where(w => w.Id == Id).FirstOrDefault();
                var amount = perfectTransaction.Payment_Amount * (1 + configfee.Addfund);
                var formPerfectPayment = new formPerfectTransaction();
                formPerfectPayment.Id = perfectTransaction.Id;
                if (PerfectMoneyAdmin.Payer != null)
                {
                    PerfectMoneyAdmin.Payer = PerfectMoneyAdmin.Payer.Replace("u", "U");
                }
                formPerfectPayment.Payee_Account = PerfectMoneyAdmin.Payer;
                formPerfectPayment.Payment_Units = "USD";
                formPerfectPayment.Payee_Name = PerfectMoneyAdmin.Name;
                formPerfectPayment.Payment_Url = domain + "/Payment/Index";
                formPerfectPayment.Status_Url = "mailto:links.fund@gmail.com";
                formPerfectPayment.Nopayment_Url = domain + "/Payment/Cancel";
                formPerfectPayment.UserId = perfectTransaction.UserId;
                formPerfectPayment.Create_Date = perfectTransaction.Create_Date;
                formPerfectPayment.Payment_Amount = amount.Value;
                formPerfectPayment.Order_Num = "Order_" + Id.ToString();
                formPerfectPayment.Cust_Num = "Customer_" + perfectTransaction.UserId.ToString();
                formPerfectPayment.V2_Hash = perfectTransaction.V2_Hash;
                //var result = db.Wallets.ToArray();
                return formPerfectPayment;
            }
        }
        public formPerfectTransaction getPerfectMoneyTransaction4Web(int Id)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                string domain = DuAnDaCapEntities.getDomain();
                if (domain == "localhost")
                    domain = "http://" + DuAnDaCapEntities.getDomain() + ":12385";
                else domain = "http://" + DuAnDaCapEntities.getDomain();
                var configfee = db.FeeConfigs.FirstOrDefault();

                db.Configuration.ProxyCreationEnabled = false;
                var UserDB = new LKVService.User();
                var userAdmin = UserDB.getUserByGroup(3);
                var PerfectMoneyAdmin = this.getAccountPerfectMoney(userAdmin.UserId);
                var perfectTransaction = db.PerfectMoneyTransactions.Where(w => w.Id == Id).FirstOrDefault();
                var amount = perfectTransaction.Payment_Amount * (1 + configfee.Addfund);
                var formPerfectPayment = new formPerfectTransaction();
                formPerfectPayment.Id = perfectTransaction.Id;
                if (PerfectMoneyAdmin.Payer != null)
                {
                    PerfectMoneyAdmin.Payer = PerfectMoneyAdmin.Payer.Replace("u", "U");
                }
                formPerfectPayment.Payee_Account = PerfectMoneyAdmin.Payer;
                formPerfectPayment.Payment_Units = "USD";
                formPerfectPayment.Payee_Name = PerfectMoneyAdmin.Name;
                formPerfectPayment.Payment_Url = domain + "/JsonTransaction/webcallback";
                formPerfectPayment.Status_Url = "mailto:links.fund@gmail.com";
                formPerfectPayment.Nopayment_Url = domain + "/Payment/Cancel";
                formPerfectPayment.UserId = perfectTransaction.UserId;
                formPerfectPayment.Create_Date = perfectTransaction.Create_Date;
                formPerfectPayment.Payment_Amount = amount.Value;
                formPerfectPayment.Order_Num = "Order_" + Id.ToString();
                formPerfectPayment.Cust_Num = "Customer_" + perfectTransaction.UserId.ToString();
                formPerfectPayment.V2_Hash = perfectTransaction.V2_Hash;
                //var result = db.Wallets.ToArray();
                return formPerfectPayment;
            }
        }
        public bool pushMoneyToWallet(double Money, int WalletId, int UserId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                try
                {
                    db.Configuration.ProxyCreationEnabled = false;
                    var wallet = db.Wallet_Detail.Where(w => w.UserID == UserId && w.WalletID == WalletId).FirstOrDefault();
                    wallet.Balance += Money;
                    db.SaveChanges();
                }
                catch (Exception)
                {
                    return false;
                }
            }
            return true;
        }
        public bool addWalletHistory(double money, int userid, int walletId, string Desc = "")
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                try
                {
                    db.Configuration.ProxyCreationEnabled = false;
                    var walletHistory = new WalletHistory();
                    walletHistory.UserId = userid;
                    walletHistory.Amount = money;
                    walletHistory.CreateDate = DateTime.Now;
                    walletHistory.WalletId = walletId;
                    if (Desc != "")
                    {
                        walletHistory.Description = Desc;
                    }
                    else
                    {
                        walletHistory.Description = this.GetNameWallet(walletId);
                    }
                    db.WalletHistories.Add(walletHistory);
                    db.SaveChanges();
                }
                catch (Exception)
                {
                    return false;
                }
            }
            return true;
        }
        public string GetNameWallet(int WalletId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var wallet = db.Wallets.Where(w => w.Id == WalletId).FirstOrDefault();
                return wallet.Name;
            }
        }
        /// <summary>
        /// Tuong - lay danh sach withdraw
        /// </summary>
        /// <param name="_status">0: pending, 1: approve , 2: cancel </param>
        /// <returns>Danh sach</returns>
        public Tuple<int, WithDrawView[]> getListWidrwal(int _status = 0, int fromRange = 0, int toRange = 100)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var withdraw = db.Withdrawals.Where(w => w.Status == _status);
                if (fromRange == 1 || fromRange == 0)
                    withdraw = withdraw.OrderByDescending(o => o.Id).Skip(0).Take(toRange);
                else
                    withdraw = withdraw.OrderByDescending(o => o.Id).Skip(fromRange).Take(toRange);
                return new Tuple<int, WithDrawView[]>(withdraw.Count(), withdraw.Select(s => new WithDrawView()
                {
                    Id = s.Id,
                    CreateDate = s.Create_Date,
                    PayMent_Method = s.Payment_Method,
                    Payment_Method_Name = db.PaymentMethods.Where(w => w.Id == s.Payment_Method).FirstOrDefault() != null ? db.PaymentMethods.Where(w => w.Id == s.Payment_Method).FirstOrDefault().Name : "N/A",
                    UserId = s.UserId,
                    UserName = db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault() != null ? db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault().UserName : "N/A",
                    WalletId = s.WalletId,
                    Status = s.Status,
                    Amount = s.Amout
                }).ToArray());
            }
        }
        /// <summary>
        /// Tuong- Cap nhat trang thai cho withdraw
        /// </summary>
        /// <param name="wdId">withdraw Id</param>
        /// <param name="_status"> trang thai</param>
        /// <returns>dung- sai</returns>
        public bool updateStatusWithdraw(int wdId = 0, int _status = -1)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var withdraw = db.Withdrawals.Where(w => w.Id == wdId).FirstOrDefault();
                    if (withdraw == null)
                        return false;
                    if (_status == -1)
                        return false;
                    withdraw.Status = _status;
                    db.SaveChanges();
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

        }
        public bool updateConfirmWithdraw(int wdId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var withdraw = db.Withdrawals.Where(w => w.Id == wdId).FirstOrDefault();
                    if (withdraw == null)
                        return false;
                    if (withdraw.Status != 1)
                        return false;
                    withdraw.IsConfirm = true;
                    db.SaveChanges();
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

        }
        public bool updateStatusWithdrawAndCode(int wdId = 0, int _status = -1, string code = "")
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var withdraw = db.Withdrawals.Where(w => w.Id == wdId).FirstOrDefault();
                    if (withdraw == null)
                        return false;
                    if (_status == -1)
                        return false;
                    withdraw.Status = _status;
                    withdraw.Code = code;
                    db.SaveChanges();
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

        }
        /// <summary>
        /// Tuong - tim WithDraw theo ID
        /// </summary>
        /// <param name="wdId"></param>
        /// <returns>WithDraw</returns>
        public Withdrawal findWithDrawById(int wdId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Withdrawals.Where(w => w.Id == wdId).FirstOrDefault();
            }
        }
        /// <summary>
        /// Get List Buy Share By UserID
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns>List PlaceOrder</returns>
        public List<BuyView> GetSharesByType(int UserId, int type = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    if (type == 0)
                    {
                        return db.PlaceOrders.Where(w => w.UserId != UserId && w.Type == type && w.Quantity > 0).OrderByDescending(o => o.UnitPrice)
                        .Select(s => new BuyView()
                        {
                            Id = s.Id,
                            Quantity = s.Quantity,
                            Unit = s.UnitPrice,
                            UserName = db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault().UserName
                        })
                        .ToList();
                    }
                    else
                    {
                        return db.PlaceOrders.Where(w => w.UserId != UserId && w.Type == type && w.Quantity > 0).OrderBy(o => o.UnitPrice)
                        .Select(s => new BuyView()
                        {
                            Id = s.Id,
                            Quantity = s.Quantity,
                            Unit = s.UnitPrice,
                            UserName = db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault().UserName
                        })
                        .ToList();
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        /// <summary>
        /// Get List PalceOrder by UserId
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public List<ShareView> GetPlaceOrder(int UserId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var placeOrder = db.PlaceOrders.Where(w => w.UserId == UserId && w.Quantity > 0).OrderByDescending(o => o.Id).AsEnumerable()
                                .Select(s => new ShareView()
                                {
                                    Id = s.Id,
                                    Price = s.TotalPrice,
                                    Quantity = s.Quantity,
                                    Type = s.Type,
                                    Unit = s.UnitPrice,
                                    DataCreate = s.CreateDate.ToString("MM/dd/yyyy"),
                                })
                                .ToList();
                return placeOrder;
            }
        }
        /// <summary>
        /// Update Share is Add and edit Share
        /// </summary>
        /// <param name="Item"></param>
        /// <returns></returns>
        public int UpdateShare(PlaceOrder Item)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var placeOrder = db.PlaceOrders.Where(w => w.Id == Item.Id).FirstOrDefault();
                    if (placeOrder != null)
                    {
                        placeOrder.Quantity = Item.Quantity;
                        placeOrder.Type = Item.Type;
                        placeOrder.UnitPrice = Item.UnitPrice;
                        placeOrder.TotalPrice = Item.Quantity * Item.UnitPrice;
                        placeOrder.Status = Item.Status;

                        db.SaveChanges();
                        return placeOrder.Id;
                    }
                    else
                    {
                        var newPlaceOrder = new PlaceOrder();
                        newPlaceOrder.Quantity = Item.Quantity;
                        newPlaceOrder.Type = Item.Type;
                        newPlaceOrder.UnitPrice = Item.UnitPrice;
                        newPlaceOrder.TotalPrice = Item.Quantity * Item.UnitPrice;
                        newPlaceOrder.UserId = Item.UserId;
                        newPlaceOrder.Status = 0;
                        newPlaceOrder.WalletId = Item.WalletId;
                        newPlaceOrder.CreateDate = DateTime.Now;
                        db.PlaceOrders.Add(newPlaceOrder);
                        db.SaveChanges();
                        return newPlaceOrder.Id;
                    }

                }
                catch (Exception)
                {
                    return 0;
                }
            }
        }
        public PlaceOrder GetShare(int ShareId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.PlaceOrders.Where(w => w.Id == ShareId).FirstOrDefault();
            }
        }
        public List<ShareTransactionView> GetShareTransactionByUser(int UserId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.ShareTransactions.Where(w => w.UserId == UserId)
                    .OrderByDescending(o => o.CreateDate)
                    .AsEnumerable()
                    .Select(s => new ShareTransactionView()
                    {
                        Id = s.Id,
                        Quantity = s.Quantity,
                        Type = s.Type == 0 ? "Buy" : "Sell",
                        Unit = s.UnitPrice,
                        UserName = db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault().UserName,
                        DateCreate = s.CreateDate.ToString("MM/dd/yyyy")
                    }).ToList();
            }
        }
        public double getBalanceShare(int UserId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var shareUser = db.Share_User.Where(w => w.UserId == UserId).FirstOrDefault();
                if (shareUser == null)
                {
                    return 0;
                }
                return shareUser.Balance;
            }
        }
        public bool exceptWalletShare(int UserId, double Fee)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var shareUser = db.Share_User.Where(w => w.UserId == UserId).FirstOrDefault();
                if (shareUser != null)
                {
                    shareUser.Balance = shareUser.Balance - Fee;
                    db.SaveChanges();
                    return true;
                }
                return false;
            }
        }
        public bool PushWalletShare(int UserId, double Fee)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var shareUser = db.Share_User.Where(w => w.UserId == UserId).FirstOrDefault();
                if (shareUser != null)
                {
                    shareUser.Balance = shareUser.Balance + Fee;
                    db.SaveChanges();
                    return true;
                }
                return false;
            }
        }
        public bool deleteShare(int ShareId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var Share = db.PlaceOrders.Where(w => w.Id == ShareId).FirstOrDefault();
                if (Share != null)
                {
                    if (Share.Type == 0)
                    {
                        this.chargeFormWallet(Share.UserId, Share.WalletId, Share.TotalPrice, "Delete Share Buy");
                    }
                    db.PlaceOrders.Remove(Share);
                    db.SaveChanges();
                    return true;
                }
                return false;
            }
        }
        public bool addShareTransaction(ShareTransaction sharetransaction)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    db.ShareTransactions.Add(sharetransaction);
                    db.SaveChanges();
                }
                catch (Exception)
                {
                    return false;
                }
                return true;
            }
        }
        public bool addToShare(int UserId, double UnitPrice, double TotalPrice, int Quantity, int type)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var ShareUser = db.Share_User.Where(w => w.UserId == UserId).SingleOrDefault();
                if (ShareUser != null)
                {
                    if (ShareUser.Balance < -1 * Quantity) return false;
                    ShareUser.Balance = ShareUser.Balance + Quantity;
                    //save transaction share
                    var shareTransactionNew = new ShareTransaction();
                    shareTransactionNew.TotalPrice = TotalPrice;
                    shareTransactionNew.UnitPrice = UnitPrice;
                    shareTransactionNew.Quantity = Quantity;
                    shareTransactionNew.Type = type;
                    shareTransactionNew.UserId = UserId;
                    shareTransactionNew.CreateDate = DateTime.Now;
                    shareTransactionNew.Status = 0;
                    this.addShareTransaction(shareTransactionNew);
                    db.SaveChanges();
                    return true;
                }

                return false;
            }

        }
        public bool buyShare(int UserId, int WalletId, int needTobuy)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //lay nhung thang ban ra
                var listShareBuy = db.PlaceOrders.Where(w => w.Type == 1 && w.UserId != UserId && w.Quantity > 0).OrderBy(o => o.UnitPrice).ToList();
                //payment methol
                foreach (PlaceOrder item in listShareBuy)
                {
                    var WalletDetail = db.Wallet_Detail.Where(w => w.UserID == UserId && w.WalletID == WalletId).SingleOrDefault();
                    if (needTobuy <= 0 || WalletDetail.Balance < item.UnitPrice)
                        break;
                    int actualQty;
                    if (needTobuy >= item.Quantity)
                        actualQty = item.Quantity;
                    else
                        actualQty = Convert.ToInt32(item.Quantity - needTobuy);
                    if (actualQty != 0)
                    {
                        //add giao dich nguoi mua
                        this.addToShare(UserId, item.UnitPrice, item.UnitPrice * actualQty, actualQty, 0);
                        //add giao dich nguoi ban
                        this.addToShare(item.UserId, item.UnitPrice, item.TotalPrice, -1 * actualQty, 1);
                        // tru tien ng mua chay roi
                        this.chargeFormWallet(UserId, WalletId, -1 * (item.UnitPrice * actualQty), "Buy Share");
                        // 0 chay
                        this.chargeFormWallet(item.UserId, 2, (item.UnitPrice * actualQty), "Sell Share");
                        needTobuy -= item.Quantity;
                        item.Quantity -= actualQty;
                        db.SaveChanges();
                    }
                }
                return true;
            }
        }
        public bool SellShare(int UserId, int needTosell)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //lay nhung thang ban ra
                var listShareBuy = db.PlaceOrders.Where(w => w.Type == 0 && w.UserId != UserId && w.Quantity > 0).OrderByDescending(o => o.UnitPrice).ToList();
                //payment methol
                foreach (PlaceOrder item in listShareBuy)
                {
                    int actualQty;
                    if (needTosell >= item.Quantity)
                        actualQty = item.Quantity;
                    else
                        actualQty = Convert.ToInt32(item.Quantity - needTosell);
                    if (actualQty != 0)
                    {
                        //add giao dich nguoi ban
                        if (!this.addToShare(UserId, item.UnitPrice, item.UnitPrice * actualQty, -1 * actualQty, 1))
                            break;
                        //add giao dich nguoi mua
                        if (!this.addToShare(item.UserId, item.UnitPrice, item.TotalPrice, actualQty, 0))
                            break;
                        if (!this.chargeFormWallet(UserId, 2, (item.UnitPrice * actualQty), "Sell Share"))
                            break;
                        //if (!this.chargeFormWallet(item.UserId, 2, -1 * (float)(item.UnitPrice * actualQty), "buy Share"))
                        // break;
                        needTosell -= item.Quantity;
                        item.Quantity -= actualQty;
                        db.SaveChanges();
                    }
                }
                return true;
            }
        }
        public Array ChartBuy(DateTime now)
        {
            var f = now.AddDays(-7);
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var data = from t in db.ShareTransactions.Where(w => w.CreateDate > f && w.CreateDate <= now)
                           group t by new { t.CreateDate.Day, t.CreateDate.Month, t.CreateDate.Year } into g
                           select new { label = g.Key.Day, value = g.Average(a => a.UnitPrice) };
                return data.ToArray();
            }
        }
        /// <summary>
        /// Get List Withdrawal
        /// 
        /// </summary>        
        /// <param name="UserId"></param>
        /// <param name="Status">0: pending, 1: approve , 2: cancel</param>
        /// <returns></returns>
        public List<PenddingCashOutView> getListWithDrawByUser(int UserId, int Status)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Withdrawals.Where(w => w.UserId == UserId && w.Status == Status).AsEnumerable().OrderByDescending(o => o.Create_Date)
                    .Select(s => new PenddingCashOutView
                    {
                        Id = s.Id,
                        CreateDate = s.Create_Date.Value.ToString("MM/dd/yyyy"),
                        StatusName = s.Status == 0 ? "Pending" : (s.Status == 1 ? "Approved" : "Cancel"),
                        PaymentMethodName = db.PaymentMethods.Where(w => w.Id == s.Payment_Method).SingleOrDefault().Name,
                        Amount = s.Amout.Value
                    })
                    .ToList();
            }
        }
        /// Select List AddFund By HoangNguyen
        /// 
        private DateTime GetDate(string a = "")
        {
            string d = Convert.ToDateTime(a).ToString("dd/MM/yyyy"); //returns 25/09/2011
            DateTime date = DateTime.Parse(d, new CultureInfo("en-GB"));
            return date;// returns 09/25/2011
        }
        public Tuple<int, LoadListAddFundManager[]> getLisAddFundWithCondition(int uid, int parentID, DateTime fromdate, DateTime todate, int fromPage = 0, int toPage = 100)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                DateTime From = GetDate(fromdate.ToString());
                DateTime To = GetDate(todate.ToString());
                db.Configuration.ProxyCreationEnabled = false;
                var sql = from U in db.UserProfiles
                          join W in db.WalletHistories.Where(w => w.WalletId == 1 && w.Amount > 0 && w.CreateDate >= From && w.CreateDate <= To && w.CreateDate != null)
                          on U.UserId equals W.UserId
                          join P in db.PaymentMethods
                          on W.PaymentMethod equals P.Id into ps
                          from L in ps.DefaultIfEmpty()
                          select new LoadListAddFundManager
                          {

                              Date = W.CreateDate,
                              UserId = U.UserId,
                              UserName = U.UserName,
                              PayMentMedthod = L.Name,
                              IDPayMent = L.Id,
                              BatChNo = W.Payment_orderid,
                              CashonDeposit = W.Amount,
                              ID = W.ID
                          };
                if (uid != 0)
                    sql = sql.Where(w => w.UserId == uid);
                if (parentID != 0)
                    sql = sql.Where(w => w.IDPayMent == parentID);
                int totalItems = sql.Count();
                if (fromPage == 0 || fromPage == 1)
                {
                    return new Tuple<int, LoadListAddFundManager[]>(totalItems, sql.OrderByDescending(x => x.ID).Skip(0).Take(toPage).ToArray());
                }
                else
                    return new Tuple<int, LoadListAddFundManager[]>(totalItems, sql.OrderByDescending(x => x.ID).Skip(fromPage).Take(toPage).ToArray());

            }
        }
        //Hàm lấy danh sách PH theo user
        public List<PHView> getListPH(int userId = 0)
        {
            //GH Status: 0:New Active | 1: Processing | 2: Bad GH |3: Confirm
            //GH Type: 0: Normal (6tr) | 1: Withdraw (1tr5) | 2: IsLock(-100% PH: 4tr5)
            //PH Status: 0:New Active | 1: Processing | 2: Bad PH |3: Confirm
            //Transfer Status: 0 : Processing | 1: Bad : 2: Complete
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                // lấy time chờ PH
                var tp = db.PH_Config.ToList().FirstOrDefault();
                var ls = db.PHs.Where(w => w.UserId == userId).AsEnumerable().Select(s => new PHView
                {
                    Id = s.Id,
                    Amount = s.Amount,
                    Extant = s.Extant,
                    Delivered = s.Delivered,
                    Status = s.Status,
                    StatusName = s.Status == null ? "New Active" : s.Status == 0 ? "New Active" : s.Status == 1 ? "Proccesing" : s.Status == 3 ? "Complete" : "Bad Report",
                    UserName = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault() == null ? "" : db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault().UserName,
                    UserId = s.UserId,
                    CreateDate = s.CreateDate == null ? "" : s.CreateDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt"),
                    OrginalDate = s.CreateDate,
                    TransferOrder = s.Status.Value != 3 ? db.TransferOrders.Where(w => w.Ph_Id != null && w.Ph_Id.Value == s.Id).ToList() : new List<TransferOrder>()
                }).OrderByDescending(o => o.Id).ToList();
                ls.ForEach(f =>
                {
                    if (f.OrginalDate != null && f.Status == 0)
                    {
                        var cd = Convert.ToDateTime(f.OrginalDate);
                        var ts = DateTime.Now.Subtract(cd);
                        if (ts.TotalDays > 0)
                        {
                            f.Remaining = "Waiting "+ (ts.Days > 0 ? ts.Days.ToString() + " days " : "") + (ts.Hours > 0 ? ts.Hours.ToString() + " hours " : "") +
                            (ts.Minutes > 0 ? ts.Minutes.ToString() + " minutes " : "");
                        }
                        else
                        {
                            f.Remaining = "0";
                        }
                    };
                    if(f.TransferOrder.Count > 0)
                    {
                        foreach (var item in f.TransferOrder)
                        {
                            var dd = Convert.ToDateTime(item.CreateDate);
                            var tdm = dd.AddHours(36);
                            var tds = tdm.Subtract(DateTime.Now);
                            if (tds.TotalHours > 0 && tds.TotalHours < 36.01)
                            {
                                item.Remaining = (tds.Days > 0 ? tds.Days.ToString() + " days " : "") + (tds.Hours > 0 ? tds.Hours.ToString() + " hours " : "") +
                                (tds.Minutes > 0 ? tds.Minutes.ToString() + " minutes " : "");
                            }
                            var confirmPH = db.ConfirmTransferPHs.FirstOrDefault(fm => fm.TransId == item.Id);
                            if (confirmPH != null)
                                item.ShowConfirm = true;
                            else
                                item.ShowConfirm = false;

                        }
                    };
                });
                return ls;
            }
        }
        //Hàm lấy danh sách GH theo user
        public List<GHView> getListGH(int userId = 0)
        {
            //GH Status: 0:New Active | 1: Processing | 2: Bad GH |3: Confirm
            //GH Type: 0: Normal (6tr) | 1: Withdraw (1tr5) | 2: IsLock(-100% PH: 4tr5)
            //PH Status: 0:New Active | 1: Processing | 2: Bad PH |3: Confirm
            //Transfer Status: 0 : Processing | 1: Bad : 2: Complete
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                // lấy time chờ PH
                var tp = db.GH_Config.ToList().FirstOrDefault();
                var ls = db.GHs.Where(w => w.UserId == userId && w.Type.Value != 1).AsEnumerable().Select(s => new GHView
                {
                    Id = s.Id,
                    Amount = s.Amount,
                    Extant = s.Extant,
                    Received = s.Received,
                    Status = s.Status,
                    StatusName = s.Status == null ? "New Active" : s.Status == 0 ? "New Active" : s.Status == 1 ? "Proccesing" : s.Status == 3 ? "Complete" : "Bad Report",
                    UserName = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault() == null ? "" : db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault().UserName,
                    UserId = s.UserId,
                    CreateDate = s.CreateDate == null ? "" : s.CreateDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt"),
                    OrginalDate = s.CreateDate,
                    TransferOrder = s.Status.Value != 3 ? db.TransferOrders.Where(w => w.Gh_Id != null && w.Gh_Id.Value == s.Id).ToList() : new List<TransferOrder>(),
                    Type = s.Type,
                    TypeName = s.Type == 0 ? "Normal" : "IsLock"
                }).OrderByDescending(o => o.Id).ToList();
                ls.ForEach(f =>
                {
                    if (f.OrginalDate != null)
                    {
                        if (f.OrginalDate != null && f.Status == 0)
                        {
                            var cd = Convert.ToDateTime(f.OrginalDate);
                            var ts = DateTime.Now.Subtract(cd);
                            if (ts.TotalDays > 0)
                            {
                                f.Remaining = "Waiting " + (ts.Days > 0 ? ts.Days.ToString() + " days " : "") + (ts.Hours > 0 ? ts.Hours.ToString() + " hours " : "") +
                                (ts.Minutes > 0 ? ts.Minutes.ToString() + " minutes " : "");
                            }
                            else
                            {
                                f.Remaining = "0";
                            }
                        }
                    };
                    if (f.TransferOrder.Count > 0)
                    {
                        foreach (var item in f.TransferOrder)
                        {
                            var dd = Convert.ToDateTime(item.CreateDate);
                            var tdm = dd.AddHours(36);
                            var tds = tdm.Subtract(DateTime.Now);
                            if (tds.TotalHours > 0 && tds.TotalHours < 36.01)
                            {
                                item.Remaining = (tds.Days > 0 ? tds.Days.ToString() + " days " : "") + (tds.Hours > 0 ? tds.Hours.ToString() + " hours " : "") +
                                (tds.Minutes > 0 ? tds.Minutes.ToString() + " minutes " : "");
                            }
                            else
                                item.Remaining = "0";
                            var confirmPH = db.ConfirmTransferPHs.FirstOrDefault(fm => fm.TransId == item.Id);
                            if (confirmPH != null)
                                item.ShowConfirm = true;
                            else
                                item.ShowConfirm = false;
                        }
                    };

                });
                return ls;
            }
        }
        //Hàm lấy danh sách Withdraw user
        public List<GHView> getListWd(int userId = 0)
        {
            //GH Status: 0:New Active | 1: Processing | 2: Bad GH |3: Confirm
            //GH Type: 0: Normal (6tr) | 1: Withdraw (1tr5) | 2: IsLock(-100% PH: 4tr5)
            //PH Status: 0:New Active | 1: Processing | 2: Bad PH |3: Confirm
            //Transfer Status: 0 : Processing | 1: Bad : 2: Complete
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                // lấy time chờ PH
                var tp = db.GH_Config.ToList().FirstOrDefault();
                var ls = db.GHs.Where(w => w.UserId == userId && w.Type.Value == 1).AsEnumerable().Select(s => new GHView
                {
                    Id = s.Id,
                    Amount = s.Amount,
                    Extant = s.Extant,
                    Received = s.Received,
                    Status = s.Status,
                    StatusName = s.Status == null ? "New Active" : s.Status == 0 ? "New Active" : s.Status == 1 ? "Proccesing" : s.Status == 3 ? "Complete" : "Bad Report",
                    UserName = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault() == null ? "" : db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault().UserName,
                    UserId = s.UserId,
                    CreateDate = s.CreateDate == null ? "" : s.CreateDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt"),
                    OrginalDate = s.CreateDate,
                    TransferOrder = s.Status.Value != 3 ? db.TransferOrders.Where(w => w.Gh_Id != null && w.Gh_Id.Value == s.Id).ToList() : new List<TransferOrder>(),
                    Type = s.Type,
                    TypeName = s.Type == 0 ? "Normal" : s.Type == 1 ? "Withdraw" : "IsLock"
                }).OrderByDescending(o => o.Id).ToList();
                ls.ForEach(f =>
                {
                    if (f.OrginalDate != null)
                    {
                        if (f.OrginalDate != null && f.Status == 0)
                        {
                            var cd = Convert.ToDateTime(f.OrginalDate);
                            var ts = DateTime.Now.Subtract(cd);
                            if (ts.TotalDays > 0)
                            {
                                f.Remaining = "Waiting " + (ts.Days > 0 ? ts.Days.ToString() + " days " : "") + (ts.Hours > 0 ? ts.Hours.ToString() + " hours " : "") +
                                (ts.Minutes > 0 ? ts.Minutes.ToString() + " minutes " : "");
                            }
                            else
                            {
                                f.Remaining = "0";
                            }
                        }
                    };
                    if (f.TransferOrder.Count > 0)
                    {
                        foreach (var item in f.TransferOrder)
                        {
                            var dd = Convert.ToDateTime(item.CreateDate);
                            var tdm = dd.AddHours(36);
                            var tds = tdm.Subtract(DateTime.Now);
                            if (tds.TotalHours > 0 && tds.TotalHours < 36.01)
                            {
                                item.Remaining = (tds.Days > 0 ? tds.Days.ToString() + " days " : "") + (tds.Hours > 0 ? tds.Hours.ToString() + " hours " : "") +
                                (tds.Minutes > 0 ? tds.Minutes.ToString() + " minutes " : "");
                            }
                            else
                                item.Remaining = "0";
                            var confirmPH = db.ConfirmTransferPHs.FirstOrDefault(fm => fm.TransId == item.Id);
                            if (confirmPH != null)
                                item.ShowConfirm = true;
                            else
                                item.ShowConfirm = false;
                        }
                    };

                });
                return ls;
            }
        }
        //Hàm lấy danh sách PH không phải Bad cho Admin
        public Tuple<int, PHView[]> getListPHForAdmin(string userName, int status, DateTime fromdate, DateTime todate, int fromPage = 0, int toPage = 25)
        {
            //GH Status: 0:New Active | 1: Processing | 2: Bad GH |3: Confirm
            //GH Type: 0: Normal (6tr) | 1: Withdraw (1tr5) | 2: IsLock(-100% PH: 4tr5)
            //PH Status: 0:New Active | 1: Processing | 2: Bad PH |3: Confirm
            //Transfer Status: 0 : Processing | 1: Bad : 2: Complete
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                // lấy time chờ PH
                var tp = db.PH_Config.ToList().FirstOrDefault();
                var ls = db.PHs.Where(w => w.Status != 2 && w.CreateDate.Value >= fromdate && w.CreateDate <= todate).AsEnumerable().Select(s => new PHView
                {
                    Id = s.Id,
                    Amount = s.Amount,
                    Extant = s.Extant,
                    Delivered = s.Delivered,
                    Status = s.Status,
                    StatusName = s.Status == null ? "New Active" : s.Status == 0 ? "New Active" : s.Status == 1 ? "Proccesing" : s.Status == 3 ? "Complete" : "Bad Report",
                    UserName = db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault() == null ? "" : db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault().UserName,
                    UserId = s.UserId,
                    CreateDate = s.CreateDate == null ? "" : s.CreateDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt"),
                    OrginalDate = s.CreateDate,
                    TransferOrder = s.Status.Value != 3 ? db.TransferOrders.Where(w => w.Ph_Id != null && w.Ph_Id.Value == s.Id).ToList() : new List<TransferOrder>()
                }).ToList();
                ls.ForEach(f =>
                {
                    if (f.OrginalDate != null && f.Status == 0)
                    {
                        var cd = Convert.ToDateTime(f.OrginalDate);
                        var ts = DateTime.Now.Subtract(cd);
                        if (ts.TotalDays > 0)
                        {
                            f.Remaining = "Waiting " + (ts.Days > 0 ? ts.Days.ToString() + " days " : "") + (ts.Hours > 0 ? ts.Hours.ToString() + " hours " : "") +
                            (ts.Minutes > 0 ? ts.Minutes.ToString() + " minutes " : "");
                        }
                        else
                        {
                            f.Remaining = "0";
                        }
                    };
                    if (f.TransferOrder.Count > 0)
                    {
                        foreach (var item in f.TransferOrder)
                        {
                            var dd = Convert.ToDateTime(item.CreateDate);
                            var tdm = dd.AddHours(36);
                            var tds = tdm.Subtract(DateTime.Now);
                            if (tds.TotalHours > 0 && tds.TotalHours < 36.01)
                            {
                                item.Remaining = (tds.Days > 0 ? tds.Days.ToString() + " days " : "") + (tds.Hours > 0 ? tds.Hours.ToString() + " hours " : "") +
                            (tds.Minutes > 0 ? tds.Minutes.ToString() + " minutes " : "");
                            }
                        }
                    };
                });
                if (!String.IsNullOrEmpty(userName))
                {
                    ls = ls.Where(w => w.UserName == userName).ToList();
                }
                if (status == 0)
                    ls = ls.Where(x => x.Status == 0).ToList();
                else if (status == 1)
                    ls = ls.Where(x => x.Status == 1).ToList();
                else if(status == 3)
                    ls = ls.Where(x => x.Status == 3).ToList();
                int totalItem = ls.Count();
                if (fromPage == 0 || fromPage == 1)
                {
                    return new Tuple<int, PHView[]>(totalItem, ls.OrderBy(x => x.CreateDate).Skip(0).Take(toPage).ToArray());
                }
                else
                    return new Tuple<int, PHView[]>(totalItem, ls.OrderBy(x => x.CreateDate).Skip(fromPage).Take(toPage).ToArray());
            }
        }
        //Hàm lấy danh sách PH là Bad cho Admin
        public Tuple<int, PHView[]> getListPHForAdminIsBad(string userName,DateTime fromdate, DateTime todate, int fromPage = 0, int toPage = 25)
        {
            //GH Status: 0:New Active | 1: Processing | 2: Bad GH |3: Confirm
            //GH Type: 0: Normal (6tr) | 1: Withdraw (1tr5) | 2: IsLock(-100% PH: 4tr5)
            //PH Status: 0:New Active | 1: Processing | 2: Bad PH |3: Confirm
            //Transfer Status: 0 : Processing | 1: Bad : 2: Complete
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                // lấy time chờ PH
                var tp = db.PH_Config.ToList().FirstOrDefault();
                var ls = db.PHs.Where(w => w.Status == 2).AsEnumerable().Select(s => new PHView
                {
                    Id = s.Id,
                    Amount = s.Amount,
                    Extant = s.Extant,
                    Delivered = s.Delivered,
                    Status = s.Status,
                    StatusName = s.Status == null ? "New Active" : s.Status == 0 ? "New Active" : s.Status == 1 ? "Proccesing" : s.Status == 3 ? "Complete" : "Bad Report",
                    UserName = db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault() == null ? "" : db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault().UserName,
                    UserId = s.UserId,
                    CreateDate = s.CreateDate == null ? "" : s.CreateDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt"),
                    OrginalDate = s.CreateDate,
                    TransferOrder = db.TransferOrders.Where(w => w.Ph_Id != null && w.Ph_Id.Value == s.Id).ToList()
                }).OrderByDescending(o => o.Id).ToList();
                ls.ForEach(f =>
                {
                    if (f.OrginalDate != null && f.Status == 0)
                    {
                        var cd = Convert.ToDateTime(f.OrginalDate);
                        var ts = DateTime.Now.Subtract(cd);
                        if (ts.TotalDays > 0)
                        {
                            f.Remaining = "Waiting " + (ts.Days > 0 ? ts.Days.ToString() + " days " : "") + (ts.Hours > 0 ? ts.Hours.ToString() + " hours " : "") +
                            (ts.Minutes > 0 ? ts.Minutes.ToString() + " minutes " : "");
                        }
                        else
                        {
                            f.Remaining = "0";
                        }
                    };
                    if (f.TransferOrder.Count > 0)
                    {
                        foreach (var item in f.TransferOrder)
                        {
                            var dd = Convert.ToDateTime(item.CreateDate);
                            var tdm = dd.AddHours(36);
                            var tds = tdm.Subtract(DateTime.Now);
                            if (tds.TotalHours > 0 && tds.TotalHours < 36.01)
                            {
                                item.Remaining = (tds.Days > 0 ? tds.Days.ToString() + " days " : "") + (tds.Hours > 0 ? tds.Hours.ToString() + " hours " : "") +
                            (tds.Minutes > 0 ? tds.Minutes.ToString() + " minutes " : "");
                            }
                            var flag = db.BadReports.Where(w => w.TransferId != null && w.TransferId.Value == item.Id).FirstOrDefault();
                            if (flag != null)
                            {
                                if (flag.PH_OR_GH == 0)
                                    item.Ph_Or_Gh = 0;//GH report
                                else
                                    item.Ph_Or_Gh = 1; //PH report
                            } 
                        }
                    };                 
                });
                if (!String.IsNullOrEmpty(userName))
                {
                    ls = ls.Where(w => w.UserName == userName).ToList();
                }
                int totalItem = ls.Count();
                if (fromPage == 0 || fromPage == 1)
                {
                    return new Tuple<int, PHView[]>(totalItem, ls.OrderBy(x => x.CreateDate).Skip(0).Take(toPage).ToArray());
                }
                else
                    return new Tuple<int, PHView[]>(totalItem, ls.OrderBy(x => x.CreateDate).Skip(fromPage).Take(toPage).ToArray());
            }
        }
        //Hàm lấy danh sách GH cho Admin
        public Tuple<int, GHView[]> getListGHForAdmin(string userName, int status, DateTime fromdate, DateTime todate, int fromPage = 0, int toPage = 25)
        {
            //GH Status: 0:New Active | 1: Processing | 2: Bad GH |3: Confirm
            //GH Type: 0: Normal (6tr) | 1: Withdraw (1tr5) | 2: IsLock(-100% PH: 4tr5)
            //PH Status: 0:New Active | 1: Processing | 2: Bad PH |3: Confirm
            //Transfer Status: 0 : Processing | 1: Bad : 2: Complete
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                // lấy time chờ PH
                var tp = db.GH_Config.ToList().FirstOrDefault();
                var ls = db.GHs.Where(w => w.Type.Value != 1).AsEnumerable().Select(s => new GHView
                {
                    Id = s.Id,
                    Amount = s.Amount,
                    Extant = s.Extant,
                    Received = s.Received,
                    Status = s.Status,
                    StatusName = s.Status == null ? "New Active" : s.Status == 0 ? "New Active" : s.Status == 1 ? "Proccesing" : s.Status == 3 ? "Complete" : "Bad Report",
                    UserName = db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault() == null ? "" : db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault().UserName,
                    UserId = s.UserId,
                    CreateDate = s.CreateDate == null ? "" : s.CreateDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt"),
                    OrginalDate = s.CreateDate,
                    TransferOrder = s.Status.Value != 3 ? db.TransferOrders.Where(w => w.Gh_Id != null && w.Gh_Id.Value == s.Id).ToList() : new List<TransferOrder>(),
                    Type = s.Type,
                    TypeName = s.Type == 0 ? "Normal" : s.Type == 1 ? "Withdraw" : "IsLock"
                }).OrderByDescending(o => o.Id).ToList();
                ls.ForEach(f =>
                {
                    if (f.OrginalDate != null && f.Status == 0)
                    {
                        var cd = Convert.ToDateTime(f.OrginalDate);
                        var ts = DateTime.Now.Subtract(cd);
                        if (ts.TotalDays > 0)
                        {
                            f.Remaining = "Waiting " + (ts.Days > 0 ? ts.Days.ToString() + " days " : "") + (ts.Hours > 0 ? ts.Hours.ToString() + " hours " : "") +
                            (ts.Minutes > 0 ? ts.Minutes.ToString() + " minutes " : "");
                        }
                        else
                        {
                            f.Remaining = "0";
                        }
                    };
                    if (f.TransferOrder.Count > 0)
                    {
                        foreach (var item in f.TransferOrder)
                        {
                            var dd = Convert.ToDateTime(item.CreateDate);
                            var tdm = dd.AddHours(36);
                            var tds = tdm.Subtract(DateTime.Now);
                            if (tds.TotalHours > 0 && tds.TotalHours < 36.01)
                            {
                                item.Remaining = (tds.Days > 0 ? tds.Days.ToString() + " days " : "") + (tds.Hours > 0 ? tds.Hours.ToString() + " hours " : "") +
                            (tds.Minutes > 0 ? tds.Minutes.ToString() + " minutes " : "");
                            }
                        }
                    };
                });
                if (!String.IsNullOrEmpty(userName))
                {
                    ls = ls.Where(w => w.UserName == userName).ToList();
                }
                if (status == 0)
                    ls = ls.Where(x => x.Status == 0).ToList();
                else if (status == 1)
                    ls = ls.Where(x => x.Status == 1).ToList();
                else if (status == 3)
                    ls = ls.Where(x => x.Status == 3).ToList();
                int totalItem = ls.Count();
                if (fromPage == 0 || fromPage == 1)
                {
                    return new Tuple<int, GHView[]>(totalItem, ls.OrderByDescending(x => x.CreateDate).Skip(0).Take(toPage).ToArray());
                }
                else
                    return new Tuple<int, GHView[]>(totalItem, ls.OrderByDescending(x => x.CreateDate).Skip(fromPage).Take(toPage).ToArray());
            }
        }
        //Hàm lấy danh sách withdraw cho Admin
        public Tuple<int, GHView[]> getListWdForAdmin(string userName, int status, DateTime fromdate, DateTime todate, int fromPage = 0, int toPage = 25)
        {
            //GH Status: 0:New Active | 1: Processing | 2: Bad GH |3: Confirm
            //GH Type: 0: Normal (6tr) | 1: Withdraw (1tr5) | 2: IsLock(-100% PH: 4tr5)
            //PH Status: 0:New Active | 1: Processing | 2: Bad PH |3: Confirm
            //Transfer Status: 0 : Processing | 1: Bad : 2: Complete
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                // lấy time chờ PH
                var tp = db.GH_Config.ToList().FirstOrDefault();
                var ls = db.GHs.Where(w => w.Type.Value == 1).AsEnumerable().Select(s => new GHView
                {
                    Id = s.Id,
                    Amount = s.Amount,
                    Extant = s.Extant,
                    Received = s.Received,
                    Status = s.Status,
                    StatusName = s.Status == null ? "New Active" : s.Status == 0 ? "New Active" : s.Status == 1 ? "Proccesing" : s.Status == 3 ? "Complete" : "Bad Report",
                    UserName = db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault() == null ? "" : db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault().UserName,
                    UserId = s.UserId,
                    CreateDate = s.CreateDate == null ? "" : s.CreateDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt"),
                    OrginalDate = s.CreateDate,
                    TransferOrder = s.Status.Value != 3 ? db.TransferOrders.Where(w => w.Gh_Id != null && w.Gh_Id.Value == s.Id).ToList() : new List<TransferOrder>(),
                    Type = s.Type,
                    TypeName = s.Type == 0 ? "Normal" : s.Type == 1 ? "Withdraw" : "IsLock"
                }).OrderByDescending(o => o.Id).ToList();
                ls.ForEach(f =>
                {
                    if (f.OrginalDate != null && f.Status == 0)
                    {
                        var cd = Convert.ToDateTime(f.OrginalDate);
                        var ts = DateTime.Now.Subtract(cd);
                        if (ts.TotalDays > 0)
                        {
                            f.Remaining = "Waiting " + (ts.Days > 0 ? ts.Days.ToString() + " days " : "") + (ts.Hours > 0 ? ts.Hours.ToString() + " hours " : "") +
                            (ts.Minutes > 0 ? ts.Minutes.ToString() + " minutes " : "");
                        }
                        else
                        {
                            f.Remaining = "0";
                        }
                    };
                    if (f.TransferOrder.Count > 0)
                    {
                        foreach (var item in f.TransferOrder)
                        {
                            var dd = Convert.ToDateTime(item.CreateDate);
                            var tdm = dd.AddHours(36);
                            var tds = tdm.Subtract(DateTime.Now);
                            if (tds.TotalHours > 0 && tds.TotalHours < 36.01)
                            {
                                item.Remaining = (tds.Days > 0 ? tds.Days.ToString() + " days " : "") + (tds.Hours > 0 ? tds.Hours.ToString() + " hours " : "") +
                            (tds.Minutes > 0 ? tds.Minutes.ToString() + " minutes " : "");
                            }
                        }
                    };
                });
                if (!String.IsNullOrEmpty(userName))
                {
                    ls = ls.Where(w => w.UserName == userName).ToList();
                }
                if (status == 0)
                    ls = ls.Where(x => x.Status == 0).ToList();
                else if (status == 1)
                    ls = ls.Where(x => x.Status == 1).ToList();
                else if (status == 3)
                    ls = ls.Where(x => x.Status == 3).ToList();
                int totalItem = ls.Count();
                if (fromPage == 0 || fromPage == 1)
                {
                    return new Tuple<int, GHView[]>(totalItem, ls.OrderByDescending(x => x.CreateDate).Skip(0).Take(toPage).ToArray());
                }
                else
                    return new Tuple<int, GHView[]>(totalItem, ls.OrderByDescending(x => x.CreateDate).Skip(fromPage).Take(toPage).ToArray());
            }
        }
        //Hàm lấy danh sách PH bị report
        public Tuple<int, PHView[]> getListPHHasReport(string userName, int status, DateTime fromdate, DateTime todate, int fromPage = 0, int toPage = 25)
        {
            //GH Status: 0:New Active | 1: Processing | 2: Bad GH |3: Confirm
            //GH Type: 0: Normal (6tr) | 1: Withdraw (1tr5) | 2: IsLock(-100% PH: 4tr5)
            //PH Status: 0:New Active | 1: Processing | 2: Bad PH |3: Confirm
            //Transfer Status: 0 : Processing | 1: Bad : 2: Complete
            //Report: action type 0: change PH | 1: risk wallet
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                // lấy time chờ PH
                var tp = db.PH_Config.ToList().FirstOrDefault();
                var ls = db.PHs.Where(w => w.Status == 2 && w.CreateDate.Value >= fromdate && w.CreateDate <= todate).AsEnumerable().Select(s => new PHView
                {
                    Id = s.Id,
                    Amount = s.Amount,
                    Extant = s.Extant,
                    Delivered = s.Delivered,
                    Status = s.Status,
                    StatusName = s.Status == null ? "New Active" : s.Status == 0 ? "New Active" : s.Status == 1 ? "Proccesing" : s.Status == 3 ? "Complete" : "Bad Report",
                    UserName = db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault() == null ? "" : db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault().UserName,
                    UserId = s.UserId,
                    CreateDate = s.CreateDate == null ? "" : s.CreateDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt"),
                    OrginalDate = s.CreateDate,
                    TransferOrder = s.Status.Value != 3 ? db.TransferOrders.Where(w => w.Ph_Id != null && w.Ph_Id.Value == s.Id).ToList() : new List<TransferOrder>()
                }).ToList();
                ls.ForEach(f =>
                {
                    if (f.OrginalDate != null && f.Status == 0)
                    {
                        var cd = Convert.ToDateTime(f.OrginalDate);
                        var ts = DateTime.Now.Subtract(cd);
                        if (ts.TotalDays > 0)
                        {
                            f.Remaining = "Waiting " + (ts.Days > 0 ? ts.Days.ToString() + " days " : "") + (ts.Hours > 0 ? ts.Hours.ToString() + " hours " : "") +
                            (ts.Minutes > 0 ? ts.Minutes.ToString() + " minutes " : "");
                        }
                        else
                        {
                            f.Remaining = "0";
                        }
                    };
                    if (f.TransferOrder.Count > 0)
                    {
                        foreach (var item in f.TransferOrder)
                        {
                            var dd = Convert.ToDateTime(item.CreateDate);
                            var tdm = dd.AddHours(36);
                            var tds = tdm.Subtract(DateTime.Now);
                            if (tds.TotalHours > 0 && tds.TotalHours < 36.01)
                            {
                                item.Remaining = (tds.Days > 0 ? tds.Days.ToString() + " days " : "") + (tds.Hours > 0 ? tds.Hours.ToString() + " hours " : "") +
                            (tds.Minutes > 0 ? tds.Minutes.ToString() + " minutes " : "");
                            }
                        }
                    };
                });
                if (!String.IsNullOrEmpty(userName))
                {
                    ls = ls.Where(w => w.UserName == userName).ToList();
                }
                if (status == 0)
                    ls = ls.Where(x => x.Status == 0).ToList();
                else if (status == 1)
                    ls = ls.Where(x => x.Status == 1).ToList();
                else if (status == 3)
                    ls = ls.Where(x => x.Status == 3).ToList();
                int totalItem = ls.Count();
                if (fromPage == 0 || fromPage == 1)
                {
                    return new Tuple<int, PHView[]>(totalItem, ls.OrderBy(x => x.CreateDate).Skip(0).Take(toPage).ToArray());
                }
                else
                    return new Tuple<int, PHView[]>(totalItem, ls.OrderBy(x => x.CreateDate).Skip(fromPage).Take(toPage).ToArray());
            }
        }
        //Hàm lấy ví cộng đồng
        public WalletPublic getWalletPublic()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.WalletPublics.FirstOrDefault();
            }
        }
        //Hàm tạo lệnh chuyển tiền từ user PH (khớp lệnh PH-GH)
        public string pairingPHAndGH(int userId = 0,int ghId = 0)
        {
            //GH Status: 0:New Active | 1: Processing | 2: Bad GH |3: Confirm
            //GH Type: 0: Normal (6tr) | 1: Withdraw (1tr5) | 2: IsLock(-100% PH: 4tr5)
            //PH Status: 0:New Active | 1: Processing | 2: Bad PH |3: Confirm
            //Transfer Status: 0 : Processing | 1: Bad : 2: Complete
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                { 
                    var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                    if (user == null)
                        return "User not found";
                    var lsPin = db.MaThes.Where(w => w.UserId == userId && w.Used != true).ToList();
                    if (lsPin.Count < 2)
                        return "You must be greater than 2 pin";
                    if (user.Status != true)
                        return "Your account has been locked";
                    var gh = db.GHs.Where(w => w.Id == ghId).FirstOrDefault();
                    if (gh == null)
                        return "GH does not exists";
                    if (gh.Status != 0)
                        return "GH incorrect status";
                    var pg = db.Packages.OrderBy(o => o.ID).FirstOrDefault();
                    //lay danh sach PH
                    var lsPH = db.PHs.Where(w => w.UserId != null && w.UserId != userId && w.Status == 1 && w.Delivered < pg.Price).OrderBy(o => o.CreateDate).ToList();
                    var ls2 = db.PHs.Where(w => w.UserId != null && w.UserId != userId && w.Status == 0 && w.Delivered == 0 && w.Extant > 0).Join(db.UserProfiles.Where(s => s.Status == true), c => c.UserId.Value, p => p.UserId, (c, p) => new { c, p }).Select(m => m.c).ToList().OrderBy(o => o.CreateDate);
                    lsPH.AddRange(ls2);
                    if (lsPH.Count < 5)
                        return "PH minimum is 4";
                    double ghAmount = gh.Amount.Value;//6tr GH | lock: 1tr5
                    string dateNow = DateTime.Now.Date.ToString("dd/MM/yyyy");
                    foreach (var item in lsPH)
                    {
                        // kiểm tra user có đang GH
                        var ghUser = db.GHs.Where(w => w.UserId != null && w.UserId == item.UserId.Value && w.Status == 1 && w.Type != 1).ToList();
                        if (ghUser.Count > 0)
                            continue;
                        //lấy tài khoản PH
                        var ph = db.UserProfiles.FirstOrDefault(f => f.UserId == item.UserId);
                        bool kq = false;
                        var phLast = db.PHs.Where(w => w.UserId != null && w.UserId == item.UserId && w.GH_Date != null && w.Status == 1).ToList();
                        if (phLast.Count == 0)
                            kq = true;
                        else
                        {
                            var lph = phLast.LastOrDefault();
                            if (lph.Delivered < pg.Price.Value)
                                kq = true;
                            else
                                kq = false;
                        }
                        if (kq)
                        {
                            
                            //Nếu tài khoản bị lock GH thì nhận về 1tr5
                            if (gh.Type == 1 || gh.Type == 2)
                            {
                                if (item.Extant < ghAmount)
                                    continue;
                                createTransferOrder(gh.Id, item.Id, item.UserId.Value, userId, ghAmount, gh.Type == 1 ? "For withdraw" : gh.Type == 2 ? "You locked GH should be deducted 100% PH" : "");
                                item.Delivered += ghAmount;
                                item.Extant -= ghAmount;
                                item.Status = 1;
                                item.GH_Date = DateTime.Now;
                                updatePH(item);
                                break;
                            }
                            if (item.Extant.Value <= ghAmount)
                            {
                                ghAmount = ghAmount - item.Extant.Value;
                                if (ghAmount > 0)
                                {
                                    createTransferOrder(gh.Id, item.Id, item.UserId.Value, userId, item.Extant.Value, "");
                                    item.Delivered += item.Extant.Value;
                                    item.Extant = 0;
                                    item.Status = 1;
                                    item.GH_Date = DateTime.Now;
                                    updatePH(item);
                                }
                                else
                                {
                                    createTransferOrder(gh.Id, item.Id, item.UserId.Value, userId, item.Extant.Value, "");
                                    item.Delivered += item.Extant.Value;
                                    item.Extant = 0;
                                    item.Status = 1;
                                    item.GH_Date = DateTime.Now;
                                    updatePH(item);
                                    break;
                                }
                            }
                            else
                            {
                                createTransferOrder(gh.Id, item.Id, item.UserId.Value, userId, ghAmount, "");
                                item.Delivered += ghAmount;
                                item.Extant -= ghAmount;
                                item.Status = 1;
                                item.GH_Date = DateTime.Now;
                                updatePH(item);
                                break;
                            }
                            string phSms = "";
                            var userPH = db.UserProfiles.FirstOrDefault(f => f.UserId == ph.UserId);
                            string fullName = "";
                            if (userPH != null)
                                fullName = userPH.HOTEN;
                            if (gh.Type == 1)
                                phSms = "[ MYBANKS-VN ] Xin chuc mung  " + ph.UserName + "-" + fullName + " da khop lenh PH ngay " + dateNow + ". Ban co 36h de hoan thanh lenh PH. Tran trong cam on.";
                            else
                                phSms = "[ MYBANKS-VN ] Xin chuc mung  " + ph.UserName + "-" + fullName + " da khop lenh PH ngay " + dateNow + ". Ban co 36h de hoan thanh lenh PH. Tran trong cam on.";
                            string resultSMS = Extension.SendSMS(ph.SDTNHARIENG.Trim(), phSms);
                            getSMSReponse(resultSMS);
                            string phEmail = "<p>MyBanks</p><p>Chúc mừng " + ph.UserName + " đã được khớp lệnh PH. Vui lòng đăng nhập và hoàn thành PH.</p><p>Chúc bạn thành công !!!</p>";
                            if (!String.IsNullOrEmpty(ph.EMAIL.Trim()))
                                SendMailPhGh(ph.EMAIL, "MyBanks ! Notification PH", phEmail);
                        }else
                            continue;
                    }
                    gh.Status = 1;
                    string ghEmail = "";
                    string ghSms = "";
                    if(gh.Type == 1)
                    { 
                      ghEmail = "<p>MyBanks</p><p>" + user.UserName + " lệnh Withdraw đã được tạo thành công .</p><p>Chúc bạn thành công !!!</p>";
                      ghSms = "[ MYBANKS-VN ] Xin chuc mung " + user.UserName +"-"+ user.HOTEN + " da khop lenh GH ngay " + dateNow + ".Dang nhap va hoan thanh GH. Tran trong cam on.";
                    }
                    else
                      ghEmail = "<p>MyBanks</p><p>Chúc mừng " + user.UserName + " đã được khớp lệnh GH. Vui lòng đăng nhập và hoàn thành GH.</p><p>Chúc bạn thành công !!!</p>";
                    if (!String.IsNullOrEmpty(user.EMAIL.Trim()))
                        SendMailPhGh(user.EMAIL, "MyBanks ! Notification GH", ghEmail);
                    //string rsp = Extension.SendSMS(user.SDTNHARIENG.Trim(), ghSms);
                    //getSMSReponse(rsp);
                    db.SaveChanges();
                    return "***";
                }catch(Exception em)
                {
                    return "Fail";
                }               
            }
        }
        //Hàm update PH
        public bool updatePH(PH ph)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                { 
                    var find = db.PHs.Where(w => w.Id == ph.Id).FirstOrDefault();
                    find.Amount = ph.Amount;
                    find.CreateDate = ph.CreateDate;
                    find.Delivered = ph.Delivered;
                    find.Extant = ph.Extant;
                    find.Status = ph.Status;
                    find.UserId = ph.UserId;
                    find.GH_Date = ph.GH_Date;
                    db.SaveChanges();
                    return true;
                }catch(Exception im)
                {
                    return false;
                }
            }
        }
        //Hàm update GH
        public bool updateGH(GH gh)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var find = db.GHs.Where(w => w.Id == gh.Id).FirstOrDefault();
                    find.Amount = gh.Amount;
                    find.CreateDate = gh.CreateDate;
                    find.Received = gh.Received;
                    find.Extant = gh.Extant;
                    find.Status = gh.Status;
                    find.UserId = gh.UserId;
                    find.Description = gh.Description;
                    db.SaveChanges();
                    return true;
                }
                catch (Exception im)
                {
                    return false;
                }
            }
        }
        //Hàm tạo lệnh chuyển| TransferOrder
        public bool createTransferOrder(int ghID = 0, int phId = 0, int userSend = 0, int userRecieve = 0, double Amount = 0, string Desc = "")
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var to = new TransferOrder();
                    to.Gh_Id = ghID;
                    to.Ph_Id = phId;
                    to.GH_Mobile = db.UserProfiles.Where(w => w.UserId == userRecieve).FirstOrDefault() != null ?
                                   db.UserProfiles.Where(w => w.UserId == userRecieve).FirstOrDefault().SDTNHARIENG : "";
                    to.PH_Mobile = db.UserProfiles.Where(w => w.UserId == userSend).FirstOrDefault() != null ?
                                   db.UserProfiles.Where(w => w.UserId == userSend).FirstOrDefault().SDTNHARIENG : "";
                    to.UserGH = userRecieve;
                    to.UserPH = userSend;
                    to.PH_Name = db.UserProfiles.Where(w => w.UserId == userSend).FirstOrDefault() != null ?
                                   db.UserProfiles.Where(w => w.UserId == userSend).FirstOrDefault().UserName : "";
                    to.GH_Name = db.UserProfiles.Where(w => w.UserId == userRecieve).FirstOrDefault() != null ?
                                   db.UserProfiles.Where(w => w.UserId == userRecieve).FirstOrDefault().UserName : "";
                    to.CreateDate = DateTime.Now;
                    to.Amount = Amount;
                    to.Description = Desc;
                    to.Status = 0;
                    db.TransferOrders.Add(to);
                    db.SaveChanges();
                    return true;
                }
                catch (Exception em) { return false; }
            }
        }
        //Hàm update status chuyển tiền
        public bool confirmTransferOrder(int transId = 0, int Status = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                //Transfer Status: 0 : Processing | 1: Bad : 2: Complete
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var tn = db.TransferOrders.Where(w => w.Id == transId).FirstOrDefault();
                    if (tn == null)
                        return false;
                    tn.Status = Status;
                    db.SaveChanges();
                    return true;
                }
                catch (Exception ep) {
                    return false;
                }
            }
        }
        //Hàm confirm PH-->check các lệnh chuyển thành công thì đưa PH vào chờ GH
        public bool confirmPH(int phId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                //PH Status: 0:New Active | 1: Processing | 2: Bad PH |3: Confirm
                //GH Type: 0: Normal (6tr) | 1: Withdraw (1tr5) | 2: IsLock(-100% PH: 4tr5)
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var ph = db.PHs.Where(w => w.Id == phId).FirstOrDefault();
                    if (ph == null)
                        return false;
                    if (ph.Status == 3)
                        return false;
                    var ts = db.TransferOrders.Where(w => (w.Ph_Id != null && w.Ph_Id == phId) && (w.Status != null && w.Status == 2)).ToList();
                    if (ts.Count == 0)
                        return false;
                    var pkg = db.Packages.OrderBy(o => o.ID).FirstOrDefault();
                    if (ts.Sum(s => s.Amount.Value) == pkg.Price.Value)
                    {
                        var od = new LKVService.OrderService();
                        ph.Status = 3;
                        //Hoàn thành PH nhảy sang chờ GH: check có bị lockPH ko
                        //check đã tồn tại GH với PH này chưa
                        var checkGH = db.GHs.Where(w => w.From_PH != null && w.From_PH.Value == ph.Id).FirstOrDefault();
                        if(checkGH == null)
                        {  
                            var gh = new GH();
                            double amount = 0;
                            var lstLock = db.LockGHs.Where(w => w.UserId != null && w.UserId.Value == ph.UserId).ToList();
                            if (lstLock.Count > 0)
                            {
                                var isLock = lstLock.LastOrDefault();
                                if (isLock.Status != null && isLock.Status.Value == true)
                                { 
                                    amount = 1500000;
                                    gh.Type = 2;
                                    gh.Description = "You locked GH should be deducted 100% PH";
                                }
                            }
                            else
                            {
                                amount = 6000000;
                                gh.Type = 0;
                            }
                            gh.Amount = amount;
                            gh.CreateDate = DateTime.Now;
                            gh.Description = "";
                            gh.Status = 0;
                            gh.UserId = ph.UserId;
                            gh.Extant = amount;
                            gh.Received = 0;
                            gh.Description = "Normal";
                            gh.From_PH = ph.Id;
                            db.GHs.Add(gh);                       
                        }
                        db.SaveChanges();
                        db.Dispose();
                        return true;
                    }
                    else
                        return false;
                }
                catch (Exception er)
                {
                    return false;
                }
            }
        }
        //Hàm confirm GH-->check các lệnh chuyển thành công thì cập nhật Complete cho GH
        public bool confirmGH(int ghId = 0)
        {
            //PH Status: 0:New Active | 1: Processing | 2: Bad PH |3: Confirm
            //GH Type: 0: Normal (6tr) | 1: Withdraw (1tr5) | 2: IsLock(-100% PH: 4tr5)
            //GH Status: 0:New Active | 1: Processing | 2: Bad GH |3: Confirm
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var gh = db.GHs.FirstOrDefault(f => f.Id == ghId);
                    if (gh == null)
                        return false;
                    var lsTrans = db.TransferOrders.Where(w => w.Gh_Id == ghId && w.Status == 2).ToList();
                    if (lsTrans.Count == 0)
                        return false;
                    var sum = lsTrans.Sum(s => s.Amount);
                    if (sum == gh.Amount)
                    {
                        gh.Status = 3;
                        if(gh.Type == 1)
                        {
                            // nếu là withdraw, lấy wallet trừ tiền
                            var wl = db.Wallet_Detail.FirstOrDefault(f => f.UserID == gh.UserId);
                            wl.Balance -= gh.Amount.Value;
                            var walletHistory = new WalletHistory();
                            walletHistory.UserId = Convert.ToInt32(gh.UserId);
                            walletHistory.Amount = gh.Amount;
                            walletHistory.CreateDate = DateTime.Now;
                            walletHistory.WalletId = 2;
                            walletHistory.Description = "Reduce "+gh.Amount.Value+" from withdraw success at "+gh.CreateDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt")+"";
                            db.WalletHistories.Add(walletHistory);
                        }
                        db.SaveChanges();
                        db.Dispose();
                        return true;
                    }
                    else
                        return false;
                }
                catch (Exception) { return false; }
            }
        }
        //Hàm tạo GH : WithDraw(1tr5) và Admin (6tr)
        public string createGHManual(int userId = 0, int type = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                //PH Status: 0:New Active | 1: Processing | 2: Bad PH |3: Confirm
                //GH Type: 0: Normal (6tr) | 1: Withdraw (1tr5) | 2: IsLock(-100% PH: 4tr5)
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                    if (user == null || user.Status == false)
                        return "User not found or User has been locked";
                    if (type == 1)
                    {
                        var wdExists = db.GHs.Where(f => f.UserId != null && f.UserId.Value == userId && f.Type == 1 && f.Status != 3).ToList();
                        if (wdExists.Count > 0)
                            return "You have withdrawal not finish";
                    }
                    var gh = new GH();
                    //For group ưu tiên: Prioritize Group
                    if (type == 0)
                    {
                        if (user.GruopID != 7)
                            return "User do not have priority ";
                        gh.Type = 0;
                        gh.Amount = 6000000;
                        gh.Extant = 6000000;

                    }//For withdraw
                    else if (type == 1)
                    {
                        gh.Type = 1;
                        gh.Amount = 1500000;
                        gh.Extant = 1500000;
                    }
                    gh.UserId = userId;
                    gh.CreateDate = DateTime.Now;
                    gh.Description = type == 1 ? "Withdraw" : "Normal";
                    gh.Received = 0;
                    gh.Status = 0;
                    db.GHs.Add(gh);
                    db.SaveChanges();
                    return "***";

                }
                catch (Exception es)
                {
                    return "Fail";
                }
            }
        }
        //Hàm cộng tiền cho PH khi chuyển tiền dưới 12h| 3% vào ví hoa hồng
        public bool bonusCompletePHEarly(int phId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                //PH Status: 0:New Active | 1: Processing | 2: Bad PH |3: Confirm
                //GH Type: 0: Normal (6tr) | 1: Withdraw (1tr5) | 2: IsLock(-100% PH: 4tr5)
                //Transfer Status: 0 : Processing | 1: Bad : 2: Complete
                db.Configuration.ProxyCreationEnabled = false;
                try {
                    var ph = db.PHs.Where(w => w.Id == phId).FirstOrDefault();
                    if (ph == null)
                        return false;
                    //lấy danh sách chuyển tiền của PH
                    var lsTrans = db.TransferOrders.Where(w => w.Ph_Id != null && w.Ph_Id == ph.Id && w.Status == 2).ToList();
                    if (lsTrans.Count == 0)
                        return false;
                    //lấy giá trị PH
                    var pack = db.Packages.FirstOrDefault();
                    var sum = lsTrans.Sum(s => s.Amount.Value);
                    if (sum < pack.Price)
                        return false;
                    // Xem hoàn thành có trươc 12h ko
                    var ts = DateTime.Now.Subtract(ph.GH_Date.Value).TotalHours;
                    if (ts < 12.09)
                    {
                        //lấy ví hoa hồng theo user
                        var rose = db.Wallet_Detail.Where(w => w.UserID == ph.UserId && w.WalletID == 2).FirstOrDefault();
                        rose.Balance += ((3 * pack.Price.Value) / 100);
                        //add profit
                        db.Profits.Add(new LKVMLMLib.Profit()
                        {
                            UserId = ph.UserId,
                            PV = 0,
                            Amount = ((3 * pack.Price.Value) / 100),
                            CreateDate = DateTime.Now,
                            Decription = "Recieved 3%  when complete PH early",
                            ProfitType = "HoaHongEarly",
                            OrderID = 0
                        });
                        //add history
                        var his = new WalletHistory();
                        his.UserId = ph.UserId.Value;
                        his.Amount = ((3 * pack.Price.Value) / 100);
                        his.CreateDate = DateTime.Now;
                        his.WalletId = 1;
                        his.Description = "3% bonus when completed early PH <" + ph.CreateDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt") + ">";
                        db.WalletHistories.Add(his);
                        db.SaveChanges();
                        db.Dispose();
                    }
                }catch(Exception ex)
                {
                    return false;
                }
                return true;
            }
        }
        // Hàm tìm Transfer Order theo Id
        public TransferOrder findTransferOrderById(int transId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.TransferOrders.Where(w => w.Id == transId).FirstOrDefault();
            }
        }
        //Hàm tạo BadReport
        public string createBadReport(int transId = 0, int type = 0,string desc = "",int actionType = 0)
        {
            //Transfer Status: 0 : Processing | 1: Bad : 2: Complete
            //actionType = 0: change PH, actionType == 1: using Risk Wallet
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                //type = 0 : "GH report" | type = 1 : "PH Report"
                db.Configuration.ProxyCreationEnabled = false;
                try {
                    var trans = db.TransferOrders.FirstOrDefault(f => f.Id == transId);
                    trans.Status = 1;
                    if (trans == null)
                        return "Transfer order not found";
                    var bad = new BadReport();
                    bad.DateReport = DateTime.Now;
                    bad.DateTrans = trans.CreateDate;
                    bad.TransferId = trans.Id;
                    bad.GH_Id = trans.Gh_Id;
                    bad.PH_Id = trans.Ph_Id;
                    if(type == 0)
                    {
                        bad.UserReport = trans.UserGH;
                        bad.UserHasReport = trans.UserPH;
                        bad.UserNameReport = trans.GH_Name;
                        bad.UserHasNameReport = trans.PH_Name;
                        bad.PH_OR_GH = 0;//GH report
                        bad.ActionType = actionType;//for GH report
                        updatePHStatus(trans.Ph_Id.Value, 2);
                        updateGHStatus(trans.Gh_Id.Value, 2);
                    }
                    else
                    {
                        bad.UserReport = trans.UserPH;
                        bad.UserHasReport = trans.UserGH;
                        bad.UserNameReport = trans.PH_Name;
                        bad.UserHasNameReport = trans.GH_Name;
                        bad.PH_OR_GH = 1;//PH report
                        updateGHStatus(trans.Gh_Id.Value, 2);
                        updatePHStatus(trans.Ph_Id.Value, 2);
                    }
                    bad.Description = desc;
                    db.BadReports.Add(bad);
                    db.SaveChanges();

                    return "***";
                } catch(Exception et) { return "Fail..."; }
            }
        }
        //Hàm lock user khi Bad chuyển PH và trừ tiền ví dự phòng hoặc lockGH cho thằng cha
        public string lockUserAndProccessParent(int userId = 0,int phId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                { 
                    var user = db.UserProfiles.FirstOrDefault(f => f.UserId == userId);;
                    if (user == null || user.UserName.Equals("root"))
                        return "Cannot find user.";
                    var parent = db.UserProfiles.FirstOrDefault(f => f.UserId == user.Parent_ID);
                    user.Status = false;
                    user.IsFirst = false;
                    if (!parent.UserName.Equals("root"))
                    {
                        var lockGH = db.LockGHs.FirstOrDefault(f => f.UserId.Value == parent.UserId);
                        if(lockGH == null)
                        {
                            var lPH = new LockGH();
                            lPH.UserId = parent.UserId;
                            lPH.Status = true;
                            db.LockGHs.Add(lPH);
                        }
                        else
                        {
                            lockGH.Status = true;
                        }
                        var sanc = new Sanction();
                        sanc.Status = true;
                        sanc.DateSanctions = DateTime.Now;
                        sanc.From_Child = user.UserId;
                        sanc.From_ChildName = user.UserName;
                        sanc.Description = "Lock PH because User <" + user.UserName + " not complete PH>";
                        sanc.PH_Id = phId;
                        db.Sanctions.Add(sanc);                      
                    }
                    db.SaveChanges();
                    return "***";
                }catch (Exception em)
                {
                    return em.ToString();
                }
            }
        }
        //Update Status PH 
        public bool updateGHStatus(int ghId = 0 , int status = 0)
        {
            //PH Status: 0:New Active | 1: Processing | 2: Bad PH |3: Confirm
            //GH Type: 0: Normal (6tr) | 1: Withdraw (1tr5) | 2: IsLock(-100% PH: 4tr5)
            //GH Status: 0:New Active | 1: Processing | 2: Bad GH |3: Confirm
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var gh = db.GHs.FirstOrDefault(f => f.Id == ghId);
                    if (gh == null)
                        return false;
                    gh.Status = status;
                    db.SaveChanges();
                    return true;
                }
                catch (Exception im)
                {
                    return false;
                }
            }
        }
        //Update Status GH 
        public bool updatePHStatus(int phId = 0, int status = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var ph = db.PHs.FirstOrDefault(f => f.Id == phId);
                    if (ph == null)
                        return false;
                    ph.Status = status;
                    db.SaveChanges();
                    return true;
                }
                catch (Exception im)
                {
                    return false;
                }
            }
        }
        //hàm lấy danh sách Admin PH (ưu tiên) theo điều kiện là New
        public List<GHView> getListGHForAdmin()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var ls = db.GHs.Where(w => w.Status == 0).Join(db.UserProfiles.Where(m => m.GruopID == 7), c => c.UserId, p => p.UserId, (c, p) => new { ph = c, us = p }).Select(s => s.ph).ToList();
                return ls.Select(s => new GHView
                {
                    Id = s.Id,
                    Amount = s.Amount,
                    Extant = s.Extant,
                    Received = s.Received,
                    Status = s.Status,
                    StatusName = s.Status == null ? "New Active" : s.Status == 0 ? "New Active" : s.Status == 1 ? "Proccesing" : s.Status == 3 ? "Confirm" : "Bad Report",
                    UserName = db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault() == null ? "" : db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault().UserName,
                    UserId = s.UserId,
                    CreateDate = s.CreateDate == null ? "" : s.CreateDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt"),
                    OrginalDate = s.CreateDate,
                    TransferOrder = db.TransferOrders.Where(w => w.Gh_Id != null && w.Gh_Id.Value == s.Id).ToList(),
                    Type = s.Type,
                    TypeName = s.Type == 0 ? "Normal" : "IsLock"
                }).ToList();
            }
        }
        //Hàm Xóa GH của User
        public string deleteGHOfUser(int ghId = 0, int userId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var gh = db.GHs.FirstOrDefault(f => f.Id == ghId);
                    if (gh == null || gh.Status != 0)
                        return "Current status cannot delete";
                    db.GHs.Remove(gh);
                    db.SaveChanges();
                    return "***";
                }
                catch (Exception im)
                {
                    return im.ToString();
                }
            }
        }
        //Hàm xóa PH theo User
        public string deletePHOfUser(int phId = 0, int userId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var ph = db.PHs.FirstOrDefault(f => f.Id == phId);
                    if (ph == null || ph.Status != 0)
                        return "Current status cannot delete";
                    db.PHs.Remove(ph);
                    db.SaveChanges();
                    return "***";
                }
                catch (Exception im)
                {
                    return im.ToString();
                }
            }
        }
        //Hàm lấy thông tin PH
        public ModalInfo findModalInfo(int userId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var md = new ModalInfo();
                var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                if (user == null)
                    return md;
                var parent = db.UserProfiles.FirstOrDefault(f => f.UserId == user.Parent_ID);
                if (parent == null)
                    return md;
                md.BankName = db.BankLists.FirstOrDefault(f => f.Id == user.BankID) != null ? db.BankLists.FirstOrDefault(f => f.Id == user.BankID).Name : "";
                md.BankNumber = user.SoTaiKhoan;
                md.FullName = user.HOTEN;
                md.ParentId = user.Parent_ID;
                md.ParentUserName = parent != null ? parent.UserName : "";
                md.ParentPhone = parent != null ? parent.SDTNHARIENG : "";
                md.ParentMail = parent != null ? parent.EMAIL : "";
                md.Email = user.EMAIL;
                md.Phone = user.SDTNHARIENG;
                md.UserName = user.UserName;
                return md;
            }
        }
        //Hàm send mail
        public  void SendMailPhGh(string toEmailAddress, string subject, string content)
        {
            var db = new LKVService.User();
            var mailSend = db.findEmailById(2);
            var fromEmailAddress = mailSend.Email.Trim();
            var fromEmailDisplayName = mailSend.Name;
            var fromEmailPassword = mailSend.Password.Trim();
            var smtpHost = mailSend.SMTPHost;
            var smtpPort = mailSend.SMTPPort;

            bool enabledSsl = true;

            string body = content;
            MailMessage message = new MailMessage(new MailAddress(fromEmailAddress, fromEmailDisplayName), new MailAddress(toEmailAddress));
            message.Subject = subject;
            message.IsBodyHtml = true;
            message.Body = body;

            var client = new SmtpClient();
            client.Credentials = new NetworkCredential(fromEmailAddress, fromEmailPassword);
            client.Host = smtpHost;
            client.EnableSsl = enabledSsl;
            client.Port = !string.IsNullOrEmpty(smtpPort) ? Convert.ToInt32(smtpPort) : 0;
            client.SendAsync(message, null);
        }
        //Hàm tạo confirm chuyển tiền của PH
        public bool createConfirmTransferPH(int transId = 0, string image = "",string desc = "")
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var trans = db.TransferOrders.FirstOrDefault(f => f.Id == transId);
                    if (trans == null)
                        return false;
                    var user = db.UserProfiles.FirstOrDefault(f => f.UserId == trans.UserPH.Value);
                    if (user == null)
                        return false;
                    var ctexist = db.ConfirmTransferPHs.FirstOrDefault(f => f.TransId == transId);
                    if(ctexist == null)
                    { 
                        var ct = new ConfirmTransferPH();
                        ct.CreateDate = DateTime.Now;
                        ct.UserId = user.UserId;
                        ct.UserName = user.UserName;
                        ct.TransId = trans.Id;
                        ct.Description = desc;
                        ct.Image = image;
                        db.ConfirmTransferPHs.Add(ct);
                    }else
                    {
                        ctexist.Description = desc;
                        ctexist.Image = image;
                    }
                    db.SaveChanges();
                    db.Dispose();
                    return true;

                }catch(Exception ep) { return false; }
            }
        }
        // Hàm lấy confirm transfer PH
        public ConfirmTransferPH findConfirmTransferPH(int transId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.ConfirmTransferPHs.FirstOrDefault(f => f.TransId == transId);
            }
        }
        // Hàm lấy Bad Report theo Id PH
        public BadReport findBadReportByPH(int phId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.BadReports.FirstOrDefault(f => f.PH_Id != null && f.PH_Id.Value == phId);
            }
        }
        // Hàm lấy response của SMS
        public void getSMSReponse(string content = "")
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try { 
                var sms = new ResultSM();
                sms.DateRecieve = DateTime.Now;
                sms.ErrorMessage = content;
                sms.SmsId = "5461";
                sms.CodeResult = "123456";
                db.ResultSMS.Add(sms);
                db.SaveChanges();
                }catch(Exception em) { }
            }
        }
        //Hàm thay thế PH khi GH admin confirm BadReport
        public string supplantTransferOrder(int transId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var transCur = db.TransferOrders.FirstOrDefault(f => f.Id == transId);
                    if (transCur == null)
                        return "Transfer Order does not exists";
                    if (transCur.Status != 1)
                        return "Status incorrect";
                    string kq = changeTransferPHBad(transCur.UserGH.Value, transCur.Gh_Id.Value, transCur.Amount.Value);
                    if (kq.Equals("***"))
                    {
                        var rGH = updateGHStatus(transCur.Gh_Id.Value, 1);
                        if (rGH)
                        {
                            transCur.Description = "[BadReport] from "+ transCur.Gh_Id + " ,because not transfer money to GH User :" + transCur.GH_Name;
                            transCur.Gh_Id = 0;
                            transCur.GH_Mobile = null;
                            transCur.Status = 1;
                            transCur.UserGH = 0;
                            db.SaveChanges();
                            return "***";
                        }
                        else
                            return "GH update not success";

                    }
                    else
                        return kq;
                }
                catch (Exception em)
                {
                    return "fail";
                }
            }
        }
        // Hàm tạo lệnh chuyển tiền thay thế cho GH khi PH bị report
        public string changeTransferPHBad(int userId = 0, int ghId = 0, double amount = 0)
        {
            //GH Status: 0:New Active | 1: Processing | 2: Bad GH |3: Confirm
            //GH Type: 0: Normal (6tr) | 1: Withdraw (1tr5) | 2: IsLock(-100% PH: 4tr5)
            //PH Status: 0:New Active | 1: Processing | 2: Bad PH |3: Confirm
            //Transfer Status: 0 : Processing | 1: Bad : 2: Complete
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                    if (user == null)
                        return "User not found";
                    var gh = db.GHs.Where(w => w.Id == ghId).FirstOrDefault();
                    if (gh == null)
                        return "GH does not exists";
                    if (gh.Status != 0)
                        return "GH incorrect status";
                    if (amount == 0)
                        return "Amount must greate 0";
                    var pg = db.Packages.OrderBy(o => o.ID).FirstOrDefault();
                    //lay danh sach PH
                    var lsPH = db.PHs.Where(w => w.UserId != null && (w.Status == 1 || w.Status == 0) && w.UserId != null && w.UserId != userId
                    && w.Delivered < pg.Price && w.Extant > 0).Join(db.UserProfiles.Where(s => s.Status == true), c => c.UserId.Value, p => p.UserId, (c, p) => new { c, p }).Select(m => m.c).ToList();
                    lsPH.OrderBy(o => o.CreateDate);
                    if (lsPH.Count < 5)
                        return "PH minimum is 4";
                    double ghAmount = amount;
                    string dateNow = DateTime.Now.Date.ToString("dd/MM/yyyy");
                    foreach (var item in lsPH)
                    {
                        //lấy tài khoản PH
                        var ph = db.UserProfiles.FirstOrDefault(f => f.UserId == item.UserId);
                        if (item.Extant.Value <= ghAmount)
                        {
                            ghAmount = ghAmount - item.Extant.Value;
                            if (ghAmount > 0)
                            {
                                createTransferOrder(gh.Id, item.Id, item.UserId.Value, userId, item.Extant.Value, "");
                                item.Delivered += item.Extant.Value;
                                item.Extant = 0;
                                item.Status = 1;
                                item.GH_Date = DateTime.Now;
                                updatePH(item);
                            }
                            else
                            {
                                createTransferOrder(gh.Id, item.Id, item.UserId.Value, userId, item.Extant.Value, "");
                                item.Delivered += item.Extant.Value;
                                item.Extant = 0;
                                item.Status = 1;
                                item.GH_Date = DateTime.Now;
                                updatePH(item);
                                break;
                            }
                        }
                        else
                        {
                            createTransferOrder(gh.Id, item.Id, item.UserId.Value, userId, ghAmount, "");
                            item.Delivered += ghAmount;
                            item.Extant -= ghAmount;
                            item.Status = 1;
                            item.GH_Date = DateTime.Now;
                            updatePH(item);
                            break;
                        }
                        var userPH = db.UserProfiles.FirstOrDefault(f => f.UserId == ph.UserId);
                        string fullName = "";
                        if (userPH != null)
                            fullName = userPH.HOTEN;
                        string phSms = "[ MYBANKS-VN ] Xin chuc mung  " + ph.UserName + "-" + fullName + " da khop lenh PH ngay " + dateNow + ". Ban co 36h de hoan thanh lenh PH. Tran trong cam on.";
                        //string resultSMS = Extension.SendSMS(ph.SDTNHARIENG.Trim(), phSms);
                        //getSMSReponse(resultSMS);
                        string phEmail = "<p>MyBanks</p><p>Chúc mừng " + ph.UserName + " đã được khớp lệnh PH. Vui lòng đăng nhập và hoàn thành PH.</p><p>Chúc bạn thành công !!!</p>";
                        if (!String.IsNullOrEmpty(ph.EMAIL.Trim()))
                            SendMailPhGh(ph.EMAIL, "MyBanks ! Notification PH", phEmail);
                    }
                    gh.Status = 1;
                    string ghEmail = "<p>MyBanks</p><p>Chúc mừng " + user.UserName + " đã được thay thế PH. Vui lòng đăng nhập và hoàn thành GH.</p><p>Chúc bạn thành công !!!</p>";
                    if (!String.IsNullOrEmpty(user.EMAIL.Trim()))
                        SendMailPhGh(user.EMAIL, "MyBanks ! Notification GH", ghEmail);
                    db.SaveChanges();
                    return "***";
                }
                catch (Exception em)
                {
                    return "Fail";
                }
            }
        }
        // Hàm tạo chuyển tiền cho GH có PH bị report và GH chọn từ ví dự phòng
        public string transferFromAdminToGHHasReport(int userId = 0, double amount = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                    if (user == null)
                        return "User not found";
                    if (amount == 0)
                        return "Amount must greate 0";
                    var wl = db.Wallet_Detail.FirstOrDefault(f => f.UserID == userId && f.WalletID == 1);
                    if (wl == null)
                        return "Wallet does not exists";
                    if (wl.Balance < amount)
                        return "Balance not enought";
                    return "***";
                }
                catch(Exception em)
                {
                    return "Fail ! please check again";
                }
            }
        }
    }
    public class ShareView{
        public int Id { get; set; }
        public int UserId { get; set; }
        public int Status { get; set; }        
        public int Quantity { get; set; }
        public int Type { get; set; }
        public double Unit { get; set; }
        public double Price { get; set; }
        public string DataCreate { get; set; }
    }
    public class WalletList
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public double? Balance { get; set; }
    }
    public class StatisticList
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Total { get; set; }
        public string Link { get; set; }
        public bool isMoney { get; set; }
    }
    public class Dashboard
    {
        public IList<StatisticList> Statistic { get; set; }
        public IList<WalletList> Wallets { get; set; }
        public double? totalwithdrawals { get; set; }
        public string level { get; set; }
        public double? sponsorBonus { get; set; }
        public double? riskWallet { get; set; }
    }

    public class formPerfectTransaction
    {
        public int Id { get; set; }
        public int UserId { get; set; }
        public string Payee_Account { get; set; }
        public string Payee_Name { get; set; }
        public double Payment_Amount { get; set; }
        public string Payment_Units { get; set; }
        public string TimeStampgmt { get; set; }
        public string Payment_Batch_Num { get; set; }
        public string Payment_Status { get; set; }
        public string Payer_Account { get; set; }
        public string Order_Num { get; set; }
        public string Cust_Num { get; set; }
        public string Interface_Language { get; set; }
        public string V2_Hash { get; set; }
        public string Status_Url { get; set; }
        public string Payment_Url { get; set; }
        public string Nopayment_Url { get; set; }
        public DateTime? Create_Date { get; set; }
        public DateTime? Modifi_Date { get; set; }
    }

    public class WalletHistoryView
    {
        public string Date { get; set; }
        public double Amount { get; set; }
        public string Transaction { get; set; }
    }
    public class WithDrawView
    {
        public int Id { get; set; }
        public int? UserId { get; set; }
        public string UserName { get; set; }
        public int? WalletId { get; set; }
        public DateTime? CreateDate { get; set; }
        public double? Amount { get; set; }
        public int? PayMent_Method { get; set; }
        public string Payment_Method_Name { get; set; }
        public int? Status { get; set; }
        public string Payer { get; set; }
    }
    public class PenddingCashOutView
    {
        public int Id { get; set; }
        public int? UserId { get; set; }            
        public string CreateDate { get; set; }
        public double Amount { get; set; }        
        public string PaymentMethodName { get; set; }
        public string StatusName { get; set; }
    }
    public class BuyView
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public int Quantity { get; set; }
        public double Unit { get; set; }
    }
    public class ShareTransactionView
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string DateCreate { get; set; }
        public string Type { get; set; }
        public double Quantity { get; set; }
        public double Unit { get; set; }
    }
    public class LoadListAddFundManager
    {
        public DateTime? Date { get; set; }
        public string UserName { get; set; }
        public string PayMentMedthod { get; set; }
        public int? IDPayMent { get; set; }
        public double? CashonDeposit { get; set; }
        public string BatChNo { get; set; }
        public int? UserId { get; set; }
        public int ID { get; set; }
    }
    public class PHView {
        public int Id { get; set; }
        public string CreateDate { get; set; }
        public double? Amount { get; set; }
        public int? UserId { get; set; }
        public string UserName { get; set; }
        public Double? Extant { get; set; }
        public Double? Delivered { get; set; }
        public int? Status { get; set; }
        public string StatusName { get; set; }
        public string Remaining { get; set; }
        public DateTime? OrginalDate { get; set; }
        public List<TransferOrder> TransferOrder { get; set; }
        
    }
    public class GHView
    {
        public int Id { get; set; }
        public string CreateDate { get; set; }
        public double? Amount { get; set; }
        public int? UserId { get; set; }
        public string UserName { get; set; }
        public Double? Extant { get; set; }
        public Double? Received { get; set; }
        public int? Status { get; set; }
        public string StatusName { get; set; }
        public string Remaining { get; set; }
        public DateTime? OrginalDate { get; set; }
        public int? Type { get; set; }
        public List<TransferOrder> TransferOrder { get; set; }
        public string TypeName { get; set; }
    }
    public class ModalInfo
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string BankNumber { get; set; }
        public string BankName { get; set; }
        public string Email { get; set; }
        public string FullName { get; set; }
        public string Phone { get; set; }
        public int? ParentId { get; set; }
        public string ParentUserName { get; set; }
        public string ParentPhone { get; set; }
        public string ParentFullName { get; set; }
        public string ParentMail { get; set; }
    }
}
